Framework:Creating a spawn manager.

Suleiman Abdullah
4 min readMay 4, 2023

Before doing this make sure you delete AI in the scene and make sure you turn it to prefab before deleting it.

In the first step, I will create the Spawn Manager script and attach it to the Spawn Manager Game Object.

Go to the Spawn Manager and create a static variable of the Spawn Manager class called _instance.

Create a public property of static, of a Spawn Manager variable called it Instance with a capital letter.

We need to get the _instance inside the above property, we do this using get accessor, then we need to check if the _instance is null. If it's null we throw an error or if it's not we return the instance.

In this step we need to Initialize the instance, we do this In the Awake method, when the scene is loading, we say the instance is equal to this script attached to this game Object.

Create an AI prefab called AIPrefab and serialize it to be able to drag and drop ai in the inspector.

Create a coroutine and Instantiate AI every 5 seconds.

Now create a public method called SpawnEnemy then startCoroutine called SpawnAIRoutine there.

To make sure AI is spawned at the first waypoint, create a transform variable and serialize it. And when we instantiate ai it makes ai Instantiated at the spawn point position.

Go to the AI script and call this function in the update method.

The best practice is to call this method inside the game Manager, so I will do that because this AI is in the project folder if I kill the first AI, the next AI won't be instantiated in the next frame, so the best practice to call this method in the Game Manager script to make sure always AI is instantiated.

This won't work, so to solve this duplicate the spawn Point A rename it as spawn Position then take the spawn point A and J, then drag and drop them inside AI. Then add that first and last waypoint to the inspector while selecting AI.

Note: If you have used many spawn points take them all, I have used A and J only.

Make sure to disable or remove the mesh if you use a cube to set waypoints.

If we play like this will have an issue we will spawn 1 enemy per frame so if your PC runs 60 frames per second you will have 60 enemies.

Solution

To solve this, create a bool variable called isAIspawned, then go to the SpawnAIRoutine.Set the bool to true after instantiating then set it to false after waiting 5 seconds.

Last go to the Spawn Manager script in the SpawEnemy method, check if the isAISpawned variable is equal to false then StartCoroutine “SpawnAIRoutine”.

Let's play and see the result.

See you in the next one.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development