Search Unity

Instantiating as a child?

Discussion in 'Scripting' started by Marscaleb, Nov 17, 2018.

  1. Marscaleb

    Marscaleb

    Joined:
    Jan 7, 2014
    Posts:
    1,037
    So I'm spawning some game objects into my scene using instantiate to have them appear relative to another object in my scene.

    This is working, but after a while I realized that I need these objects to be children of the object that spawns them, because I need their movement to continue to be relative to that original object. ie, they need to rise/fall when the original object rises and falls. And it seems to me that the easiest way to ensure this is to parent them to the original object.

    So is there a way to spawn an object (like with instantiate) that will make that object be parented to the object who spawned them?
     
  2. santiagolopezpereyra

    santiagolopezpereyra

    Joined:
    Feb 21, 2018
    Posts:
    91
    Yes. The Instantiate() method takes several arguments; some are mandatory (the object you want to instantiate, for example) and some are optional; meaning you can leave them blank and Unity will have a default value for your empty parameter. This is the case for the Transform parent parameter. For more info, look here: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

    To make your instantiated object a child of other object, simply pass the parent as the second parameter.

    Code (CSharp):
    1. Instantiate(someObject, someParent);
    In your case, since you want the object that spawns them to be the parent,

    Code (CSharp):
    1. Instantiate(someObject, this.transform);
     
    Janna_Ukoko and Kurt-Dekker like this.
  3. Marscaleb

    Marscaleb

    Joined:
    Jan 7, 2014
    Posts:
    1,037
    Ah, I see! I feel a bit embarrassed that I didn't look that up myself. For some reason I was expecting it to be a separate function, like maybe a "instantiateAsChild()" or something.

    After trying it out, it looks like if my parent actor is ever moving while the child gets instantiated, the object just stays stuck in the same place relative to the parent, and doesn't move like it is supposed to.
    Of course, this is probably an error in my code, not in the instantiate function, so I'll just have to track this down on my own.

    But thanks for the response!
     
  4. santiagolopezpereyra

    santiagolopezpereyra

    Joined:
    Feb 21, 2018
    Posts:
    91
    Try using the worldPositionStays paremeter and set it to false, so that your Instantiate() method looks like this:

    Code (CSharp):
    1. Instantiate(yourObject, this.transform, worldPositionStays:false);
    This makes it so that the instantiated object's position is relative to the parent's position. Perhaps this will solve the problem :)
     
    Cornewaffle and Janna_Ukoko like this.