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

Why can't we instantiate root-level GameObjects to the scene that owns context?

Discussion in 'Scripting' started by wheee09, Jan 14, 2019.

  1. wheee09

    wheee09

    Joined:
    May 21, 2018
    Posts:
    68
    It's odd that we have to specifically set the active scene before we can instantiate root level GameObjects in that scene.

    Odd because we can easily instantiate a GameObject and set the parent irrespective of what the active scene is.

    The use case is the example of loading a level composed of multiple scenes. Each scene has scripts that run via Start() that create root-level GameObjects to render the level. It would make more sense for the script to run within the context of the owning scene.

    Otherwise, one would argue that:
    Given that the active scene is SceneB and I create a GameObject Child to GameObject Parent (that belongs Scene A)...
    When I unload SceneB...
    Then GameObject Child should be destroyed.

    (Which is not the case)

    The workaround is to have GameObject instances placed in the scene and simply use them as anchors/references.

    Thoughts?
     
  2. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,591
  3. wheee09

    wheee09

    Joined:
    May 21, 2018
    Posts:
    68
    Sure, that's possible - it just seems a bit unnecessary. If I'm a script running from a gameobject of a scene, then I would rather the default behaviour where instantiated root gameobjects get added to the same scene as opposed to the active scene.

    Or have an initialization method that allows you to specify the scene as an additional parameter (like the parent transform parameter).

    Anyway, I'm probably overthinking it.
     
  4. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,591
    Any reason you don't write an "Instantiate" method yourself and move the gameObject to the appropriate scene there?
     
  5. wheee09

    wheee09

    Joined:
    May 21, 2018
    Posts:
    68
    That's what I ended up doing. It's just one of those things that irk me a bit. Especially when there's a warning about the inefficiency of setting the parent of a gameobject after object instantiation.

    I can only assume that the same would apply for moving an object from the "active" scene to the scene of choosing.