Just a quick pro-tip here today. Now that we are endlessly spawning new game objects, you might have noticed during game play the Hierarchy window gets pretty cluttered, pretty fast.
In a much larger game, after longer game play this might get quite cumbersome. Now, none of this matters to the player, as the editor is not visible to them. But to yourself and other developers it might get tedious to scroll through a bunch of things you don’t happen to need right now. Sure, you’ll be glad they are there when needed, but not when you are looking for something else.
Fortunately, Unity gives us a way to cleanup and organize our game object Hierarchy. First, we create an empty game object as a child of the Spawn Manager and name the new object, ‘Enemy Container.’
Now, in our Spawn Manager script, we add a variable to hold the reference to the container. We then add the additional step of saving our newly instantiated Enemy game object to a local variable long enough for us to assign new Enemy Container as the parent game object of the Enemy game object. In particular, we assign this to the parent of the Enemy Transform, not the Enemy Game Object itself (you might recall I once said the Game Object and Transform were only usually synonymous).
using System.Collections;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
[SerializeField] private bool keepSpawning = true;
[SerializeField] private GameObject enemyPrefab;
[SerializeField] private GameObject enemyContainer;
void Start()
{
StartCoroutine(SpawnRoutine());
}
IEnumerator SpawnRoutine()
{
while (keepSpawning)
{
GameObject newEnemy = Instantiate( enemyPrefab
, new Vector3(Random.Range(-11f, 11f), 8, 0)
, Quaternion.identity);
newEnemy.transform.parent = enemyContainer.transform;
yield return new WaitForSeconds(Random.Range(2f, 5f));
}
}
}
Running this now, we see all our Enemy game objects are neatly stored in a collapsible game object we can leave closed and only expand when needed.
P.S. Don’t forget to drag the Enemy Container game object over to Inspector and drop it in the variable we created.