Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Instantiate a prefab as a children

Discussion in 'Scripting' started by cybervalie, Feb 4, 2010.

  1. cybervalie

    cybervalie

    Joined:
    Sep 27, 2009
    Posts:
    94
    Hello :D

    I would like to instantiate a prefab in children of the first person controler, for it follow his movements.

    The instantiate happend when i press a button and self destroy 10 seconds after (is a magic effect).
     
  2. damien_oconnell

    damien_oconnell

    Joined:
    Dec 24, 2009
    Posts:
    58
    Hello! :)

    try:

    Code (csharp):
    1. var firstPersonController:Transform;
    2. var prefabEffect:GameObject;
    3.  
    4. function  Start()
    5. {
    6.    var go = Instantiate(prefabEffect) as GameObject;
    7.    go.transform.parent = firstPersonController;
    8. }
     
  3. cybervalie

    cybervalie

    Joined:
    Sep 27, 2009
    Posts:
    94
    thank you very much for this, i will try it :)
     
  4. mcnikolas

    mcnikolas

    Joined:
    Sep 13, 2009
    Posts:
    42
    If you want to instantiate under a certain gameObject do that :

    temp = Instantiate(....);

    temp.transform.parent = transform;

    This will make the instantiated object the child of the Object that holds the script.Adjust it to your needs.
    Hope that helps ;-)
     
    zachmccormick11 likes this.
  5. Kudorado

    Kudorado

    Joined:
    Nov 28, 2015
    Posts:
    10
    work perfectly , thanks you so much !
     
  6. Pavan-Soneji

    Pavan-Soneji

    Joined:
    Apr 29, 2016
    Posts:
    1
    Thanks Bro.
     
  7. gislersoft

    gislersoft

    Joined:
    Apr 11, 2020
    Posts:
    1
    And to preserve original prefab transformations use:

    Code (CSharp):
    1. GameObject prefab = Resources.Load<GameObject>(pathToPrefab);
    2.  
    3. GameObject object = Instantiate(prefab) as GameObject;
    4.  
    5. object.transform.SetParent(parentObject.transform);
    6.  
    7. // Preserve original transformations
    8. object.transform.localPosition = prefab.transform.localPosition;
    9. object.transform.localRotation = prefab.transform.localRotation;
    10. object.transform.localScale = prefab.transform.localScale
     
    Fr13nd1 likes this.