Instantiate inside parent

Hi, really enjoying the course so far. I was just looking at the project and was sick of my hierarchy filling up with all the grid visual components so I am now instantiating them with “GridSystemVisual” as the Parent, this seems reasonable to me as it should always be present and should never move, is there something I have failed to consider here ?

I think that should be fine, GridSystemVisual isn’t going to change its position or scale or get destroyed, etc.

If you wanted to be extra safe, you can simply create an empty transform to act as the dedicated parent.

This is exactly what I do, and it’s as simple as adding the GridVisualSystem’s transform as another parameter to Instantiate().

Transform gridSystemVisualSingleTransform = Instantiate(
        gridSystemVisualSinglePrefab,
        LevelGrid.Instance.GetWorldPosition(gridPosition),
        Quaternion.identity,
        transform);
1 Like

I had issues for a long time with this (mental issues, not game issues). At some point I realised it doesn’t matter because it’s only at runtime - when no-one is ever going to see it once the game is built. If there’s code in these instantiated objects that depend on a parent then it matters, but if it’s just because you don’t like what it looks like in the hierarchy in the editor, it doesn’t. That being said, setting its parent doesn’t hurt.

Well, it makes debugging somewhat easier when the hiearchy isn’t cluttered up so much with tons of cloned prefab instances… :wink:
The main reason I can think of that requires an object to be on the root level would be calling DontDestroyOnLoad() (which would re-parent the object into the “DontDestroy” area, so to say)…
Having them neatly folded away might also be useful in cases you might want to do something with them since you could then easily iterate over them.

foreach( Transform t in transform)
{
  // do something with all children of this object
}
2 Likes

Privacy & Terms