Part 6: GameManager & Spawning Objects

Christiane Snyder

There are a lot of objects moving and being created in this game, so we are going to create a GameManager to track all of them.


Create an empty game object named “GameManager” in your scene.

Now create a matching C# script named GameManager.cs. Even though this script will handle a few more aspects of gameplay, we’ll only worry about spawning the obstacles and powerups for now.


Attach GameManager.cs to the GameManager object and drag the Good and Bad prefabs into their corresponding slots.


The game should have more obstacles than power-ups, so increase the number in the random number generator’s range. A max of three, will create a ⅓ chance that a powerup will be spawned and a ⅔ chance that an obstacle will be spawned next.


Since the spaceships cannot be destroyed, if the game manager were to spawn spaceships/power-ups infinitely the lanes would become extremely crowded as the game progressed. To prevent congested lanes, we are going to keep track of all the objects spawned, so that we can cap the number created.

Add two Lists (from the ‘System.Collections.Generic’ header) that will hold each type of spawnable object and before spawning a new obstacle.


Now the GameManager will run checks on how many spaceships and power-ups are currently in the scene before generating any additional objects.

It’ll only create another spaceship if the random number is greater than 0 AND the number of spaceships in the scene is less than 9. A new power-up will be produced if the random number generator produces a 0 OR there is the maximum number of spaceships and there are 2 or less power-ups in the scene.

This additional check for the powerups accounts for the case that the player is still playing after the maximum number of spaceships is reached and there is a low number of power-ups to interact with.

To accurately keep track of these objects’ count, they also need to be removed from their respective lists before they are destroyed from the scene. To make this easier, we’ll handle reactions to collisions inside of GameManager.cs. Add a RemoveObject(GameObject obj) function to the GameManager script that will process the gameobjects that the player hits:


Add a reference to the GameManager script inside Player.cs. Then call RemoveObject on this new GameManager reference in OnCollisionEnter: