Hey and welcome!
Got a nice short one for you here. In the last article we sorted out a spawner for our game to spawn enemies however you may have noticed that your hierarchy started looking something like this after a while:
So we’re going to fix that to make things a bit cleaner. First let’s create an empty object within our spawner object called Enemy_Container which will be used to contain all these.
Then we’ll want to add this variable into our SpawnBehaviour script and then assign that Enemy_Container object to it similar to how we assigned our Enemy prefab to our _enemy variable from before:
private GameObject _enemyContainer;
Now it’s just a case of touching up our code for a Coroutine from last time:
Vector3 position = new Vector3(Random.Range(-10.7f, 10.7f), 6.2f, 0);
GameObject enemy = Instantiate(_enemyPrefab, position, Quaternion.identity);
enemy.transform.parent = _enemyContainer.transform;
yield return new WaitForSeconds(5.0f);
The main difference here is that we’re putting the Enemy prefab that we’re instantiating into an enemy variable of type GameObject. We’re doing this so that we can access the parent in our Enemy object and assign that to our Enemy_Container making that the new parent of our Enemy object.
Since our Enemy is being parented to the container you’ll get something like the above that makes things a good deal neater which is very cool stuff.
That’s all from me here, not too much left to say on this though the applications of this can go pretty far depending on the game. As an example it would be pretty handy in a bullet hell game where you have multiple different enemy types firing off hundreds of their own laser/bullet instances at a time you can put each one into its own separate container to prevent all out anarchy happening in your hierarchy.