Here are two tips that I found useful when instantiating new objects:
- When spawning multiple objects, use a parent object.
Spawning multiple objects like the grid cells in this video will cause a lot of objects, named the same way, to get added to the game hierarchy window during runtime. This makes potential subsequent debugging much more annoying.
What I do, is create an empty GameObject just before the loop, and use it as a parent in the Instantiate call (the last argument to Instantiate is a parent), something like this:
GameObject parentCell = new GameObject("GridCellVisuals");
for (...) {
...
Instantiate(_singleCellVisualPrefab, LevelGrid.Instance.GetWorldPositionAt(gp), Quaternion.identity, parentCell.transform);
...
}
This results in an easier to navigate hierarchy.
(btw. one could also rename each of the cells to include its coordinates, using Object.name)
- Explicitly use the desired component type instead of generic
Transform
.
You donât need to pass prefabs asTransform
- it can be the type of the component we will anyway cast it down to later (note: this post originally said âtype of prefabâ which does not make sense - see the responses).
So use:
[SerializeField]
private SingleCellGridSystemVisual _singleCellVisualPrefab;
for setting the prefab in the engine - this will protect you from dragging the wrong prefab in there.
Additionally, this will work with Instantiate
- the only difference is that it will immediately return the relevant component instead of Transform
. But thatâs exactly what we want here, since we end up with:
SingleCellGridSystemVisual newCell = Instantiate(_singleCellVisualPrefab, LevelGrid.Instance.GetWorldPositionAt(gp), Quaternion.identity, parentCell.transform);
instead of having to additionally GetComponent
(and deal with null
s when we dragged a wrong prefab in).