Spawning your game object in Unity

Samarth Dhroov
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.

Unity

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.
C#
Unity
  • Second, declare the coroutine and add a yield statement that will have a delay of 3 seconds.
C#
  • Third, declare the instantiate function and pass in the required parameters and call the coroutine to let the show begin.
C#

With the above implementation, the final result shall resemble something shown below.

Unity

Thank you very much

--

--

No responses yet