Spawning your game object in Unity
2 min readMay 10, 2021
When you have an interest in bringing in the wrath of enemies on your player, basically you are going to spawn your enemy object at n intervals from random locations.
The location and n intervals configs will be taken care of through the transform component and coroutines respectively.
Let’s get into Unity to first introduce a behavior object by creating an empty game object and then a script named “SpawnManager”. Go ahead and attach the script also.
Now, the task at hand is to do the following.
- In the coroutine, have a while loop that will keep running as long as the condition is true. (This is for the sake of simplicity here. In the actual game, do not have a never ending loop :) )
- In there, keep instantiating the prefab that you are interested to spawn. (If your prefab is not ready, go ahead make one.)
- Have the yield statement wait for 3 seconds before spawning the next prefab in the game.
Let us get into Visual Studio to write some code.
- First, declare a serialized field in the spawn manager script and then get the prefab assigned to it that you want to spawn.
- Second, declare the coroutine and add a yield statement that will have a delay of 3 seconds.
- Third, declare the instantiate function and pass in the required parameters and call the coroutine to let the show begin.
With the above implementation, the final result shall resemble something shown below.
Thank you very much