Adventures in GameDev with GameDevHQ: Day 17, spawning objects in Unity without the clutter

I also learned how to tidy up the spawning by instantiating the enemies inside of their own enemy container. It’s easy to do, just create a new empty inside of the enemy spawner, name it Enemy_Container. create a variable in the script like you did with the prefab called something like _enemyContainer and drag the actual empty into it.

and to spawn the enemy inside of that container, you add a little bit to the instantiate line:

GameObject newEnemy = Instantiate(_enemyPrefab, spawnPosition, Quaternion.identity);

Before, the enemy would just spawn and be thrown into the wild. Here, we take it as its being born, tame it, and give it a name and then we work on adopting it.

newEnemy.transform.parent = _enemyContainer.transform;

remember we can only access an objects transform, and since an enemyContainers natural state is GameObject, trying to assign two different types will not work so you have to specify both to be transforms.

I also learned how to stop the spawner when the player died by creating a new boolean variable for the while loop called _stopSpawning. It’s initially set to false so the while is originally set to check if it’s not stopped:

while(!_stopSpawning){

Then create a new public method called OnPlayerDeath()

Then back in the Player, we’ll create a reference to the SpawnManager:

in void Start():

You have to be sure the name in the Find() field matches exactly that in the Unity editor, otherwise it won’t work.

Now in the players Damage() function, just before the player is destroyed, we’ll access the spawnmanagers OnPlayerDeath function:

The player will call the OnPlayerDeath function in the spawn manager, setting the _stopSpawning to true, and stopping the spawning!

Because the while checks for the reverse, setting the stopSpawning to true will return false in the while effectively turning it off. So let’s test it! I changed time to wait to 1 so we don’t have to wait as long to test.

As you can see, the spawner stops spawning enemy ships/cubes as soon as the player dies! Mission successful!

cartoonist, game artist, and wanabe gamedev.