Search Unity

Instantiate Make Object a Child

Discussion in 'Scripting' started by vanutella, Nov 21, 2017.

  1. vanutella

    vanutella

    Joined:
    Jun 6, 2017
    Posts:
    10
    Hello,
    I'm pretty new to scripting (C#) and I'm working on an App where new Prefabs are spawned.
    Now I can't find a way to make my Object, which I instantiate, as a Child.

    So it's
    Instantiate(boxPrefab);
    but I need it to be a child of my Panel. So my Prefab is not moving or transformed in any way.
    My Prefab ist called "boxPrefab" and my Panel is called "buttonPanel" as public GameObject.

    Could anyone help me out just really quickly?

    Thank you!
     
  2. pk_Holzbaum

    pk_Holzbaum

    Joined:
    Jul 26, 2012
    Posts:
    95
    Just set the parent transform after the prefab.

    Code (CSharp):
    1. public static Object Instantiate(Object original, Transform parent);
    You can also store a reference to the instantiated object and change the values after the creation of the object.

    Code (CSharp):
    1. GameObject object = Instantiate(Object original, Transform parent);
     
  3. laxbrookes

    laxbrookes

    Joined:
    Jan 9, 2015
    Posts:
    235
    Once you have a reference to your gameobject you should be able to set it's parent with the .SetParent method.

    Code (csharp):
    1.  
    2. GameObject box = Instantiate(boxPrefab);
    3. box.Transform.SetParent(parent.transform, true);
    4.