Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question [Solved]Instantiate Creating Orphans

Discussion in 'Scripting' started by DeusXM, May 16, 2023.

  1. DeusXM

    DeusXM

    Joined:
    Mar 12, 2020
    Posts:
    2
    So I am instantiating a small level around an object, and the level is meant to be a child to that object. The issue is that the level, no matter what I try ends up a sibling to the object.

    It is a single line of code so I'm kind of at a loss as for what to do.

    currLevel = Instantiate(levelPrefabs[rand],transform.position,Quaternion.identity,transform);

    This line is being run from a script attached to the object.
    Any advice is appreciated.
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,082
    The bolded parameter is used to specify the parent object. Remove that and it should stop.
     
    Kurt-Dekker likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,495
    It's true that it's just a single line of code. However it depends on where and from where that line of code is executed and what exact object "transform" refers to in this instance. You really should add more background info as we have to guess and speculate about your setup.

    Anyways I would always start with adding a Debug.Log right above the Instantiate line and set the context parameter to your "transform" reference. That way you can see what object that transform actually IS.

    Code (CSharp):
    1. Debug.Log("Going to instantiate level and try to parent it to this", transform);
    When you click on that log message in the Unity editor, it will show you which object you actually passed to the Log method. My guess would be that the object in question is either not in the scene (may be a prefab object) or something other is wrong with that object. Though that's why the event chain is important. Some people make the mistake to hook up prefab objects to button click events. So you may call a method on the prefab object instead of an object in the scene. You can not parent an instantiated object to a prefab asset, only to prefab instances that live in the scene or to ordinary gameobjects in the scene.
     
  4. DeusXM

    DeusXM

    Joined:
    Mar 12, 2020
    Posts:
    2
    I am dumb, there are 2 instantiate statements and I only modified one of them. The debug.log showed me that. Sorry lol.