Creating a spawning mechanism
Today we are going to be looking at how we can go about creating a method to introduce an object that will be used to spawn in a new wave of enemies. First, we shall create our asteroid and attach all the applicable components to it:
Now, let’s introduce some rotation to our object so it gives it a bit more of a feel of flying aimlessly through space. To do so, we simply go into our script and write our code similar to that of having our objects move, but this time we are going to go with Rotate rather than Translate:
As to how this looks in the game, let’s take a look:
As we can see, the rotation was rather slow to start, so we can use the slider next to to rotation speed on the script component and increase it to a value we like more. Now that we have it moving like we want, let’s get it to interact with our laser so that it is destroyed upon impact.
First, let’s make an explosion prefab to work with so we can attach it to our asteroid:
Once we have an explosion object in our hierarchy, we can simply apply our explosion animation to it like we did with our enemies:
Next, we got to go to our asteroid script and write the code needed for the interaction with the laser just as we had done before with the enemy interactions.
As we can see, we have to create a OnTrigger event for our asteroid to work off of. From here, we simply just instantiate the explosion that we created to show the death of the asteroid. We have to be sure to destroy both the laser that hits the asteroid along with the asteroid itself. We add a slight delay so it looks a bit better. Once we get all of this done, we can now try it in our game to see how it all looks:
However, the issue is now that we have an explosion clone that will just sit in our hierarchy. Having 1 isn’t too bad, but it can start to become a big use of resources if we decide to have a lot of asteroids in the game, so let’s make a quick script for the explosion and simply just have it there for 1 job, destroy the object.
Now, let’s test it out and see if the explosion disappears from our hierarchy:
Finally, let’s give this asteroid more of a purpose and have it there so that we can spawn waves of enemies from it. First, let’s go over to our spawn manager script and put our spawning routines into a public void so that we can interact with it from our asteroid script:
From here, let’s go back to our asteroid script and have it call the new routine when we destroy it.
From here, we can see what happens in our game:
We now have spawning the moment our asteroid is destroyed, but it just doesn’t feel good, so let’s slow down the initial spawn rate a little bit:
And there we have it. We have now created an object, attached an explosion to it and allowed it to be the start of our spawning routines. Next, we will look into adding some effects onto our player.