Project 1: Space Shooter
Instantiating and destroying GameObjects in Unity
With short introduction to Prefabs

For my space shooter to actually have some substance it needs more GameObjects than just the Player object. The first thing that comes to my mind from this is to have some sort of firing mechanism, after all it is a shooter style game. So what does that need?

Lots and lots of lasers which can be seen on screen when fired, then movement for them, and lastly something to handle them when they are expected to expire. That means that the lasers have to be created in a different way from the Player object, largely because no one knows how many lasers the player decides to fire.
How to achieve this? Unity has a system called Prefab, which allows the developer to make a GameObject with whatever it needs to function properly and store it as an Asset, so that it can be used and reused as many times needed. So all I have to do is to make a folder called Prefabs, then to add a new Prefab called Laser, add a script called Laser and attach that to the Prefab and done.

On the Player objects script I have to add a firing mechanism, I choose the spacebar to fire my lasers, and every time it is pressed it instantiates a new Laser object. To do this I have to call an aptly named Instantiate method, which requires the object that I want to instantiate, its position and rotation as arguments. I want the Laser object to appear just above my Player object, that is why I have to add a small offset to my Player object’s x-position for this to happen. The method also requires me to set the Laser object’s rotation, since the default rotation is fine with me, I use the Quaternion.identity to achieve that.
Now onto scripting my laser. Since my Laser object only needs simple upward movement, I won’t delve on that here. Instead I concentrate on what will happen to my Laser objects once they are fired. If nothing is done they will move upwards for all the eternity, or as long as the game is running and it has enough memory to handle all the instantiated objects.

To avoid any issues with limited amount of memory, I have to delete the Laser objects at some point. Good place to do this is once they are off screen. And to do the deletion, all I have to do is to call the method Destroy with the argument gameObject. Now, I have added the word this on it to make it more clear, for me and anybody else who reads my code, that I’m destroying this particular GameObject, but Unity itself doesn’t need it, the gameObject suffices.

And that is how to use methods Instantiate and Destroy in Unity and how to make Prefabs.