Fire the Laser! Instantiating Game Objects in Unity
Another exciting addition to my Space Shooter 2D game is the ability to fire a laser. This requires the the Instantiation of game objects, so let see how this is used in my game.
Let’s talk about what Instantiate is and how to use it. When you Instantiate a Game Object, you are simply creating a Game Object. These Game Objects are ones that you are going to use over and over again, such as projectiles, collectibles, enemies, etc. In my game example, the Game Object is the laser being fired from the Player. The first thing I needed to do was created the Game Object and set it up.
After the Game Object was created, it needs to be turned into a Prefab. A Prefab is a Game Object that has already been setup and will be used multiple times in a game. To do this is quite simple, just create a Prefabs folder and drag and drop the Game Object you want to make into a Prefab from the Hierarchy to the folder and done! The Game Object will turn blue letting you know it is a Prefab.
After the Game Object is made into a Prefab, you need to ask yourself, “When will this be Instantiate or created?” In my case, the laser will be Instantiate every time the Player press the Space bar, so this is Instantiation needs to be added to my Player script.
To use the Prefab, we are going to make a handle for it by using a private GameObject variable and make it a [SerializeField] so we can assign the Prefab in the Inspector.
Now that the Laser Prefab has been assigned, we can make reference to it when we use Instantiate. Instantiate requires 3 things.
- The Game Object to be created (Laser Prefab).
- The position of the Game Object when it is created (the Player’s position plus and offset).
- The rotation, which is not needed in this instance.
This is all placed inside of a method because more will be added, keeps the code organized and easier to debug if there is an issue with firing.
With the firing mechanic in place, I want to check to see if the Player has hit the Space Bar and if so, then we can call the Fire Laser method. We now have a firing mechanic!