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 object as child of a clone

Discussion in 'Scripting' started by Tornado77, Aug 16, 2019.

  1. Tornado77

    Tornado77

    Joined:
    Nov 14, 2018
    Posts:
    83
    Hello, how can I instantiate an object as child of a clone? I need to instantiate the first object and then instantiate another object as child of the previously instantiated object, how can I do that ?
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    Instantiate method has overload accepting transform instance to set it as parent of instantiated object. So you just need to instantiate first object and then call that overload with first object's transform.

    Code (CSharp):
    1. var first = Instantiate(prefab1);
    2. var second = Instantiate(prefab2, first.transform);
    https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
     
    Kurt-Dekker and Tornado77 like this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    What @palex-nx said is spot-on... I would only add that I suggest using the templated version of Instantiate:

    Code (csharp):
    1. var first = Instantiate<GameObject>(prefab1);
    2. var second = Instantiate<GameObject>(prefab2, first.transform);
    As an aside and completely unrelated to your problem, I also strongly suggest never using Resources.Load(); Instead use Resources.Load<T>(); so that if you have two assets named the same (such as a texture and a material), you will consistently get what you intend rather than having it sometimes cast to a null.