2D Shooter: Instantiating Objects

In the last article I wrote about the 2D shooter game, I explained how to move the player and keep it within a boundary. Now its time to add some action; its not a shooter game without something to shoot. Let’s create some lasers!

Before we can actually shoot anything though, we need to make an object to represent the laser. It will also need to spawn whenever a key is pressed.

In code terms: we need to write a script to instantiate an object if the right condition is met. The condition is the key press.

First lets make a folder for prefabs in the assets folder in unity. A prefab is an object that will be replicated many times and allows us to be able to modify all of them at once if the need arises.

So now go to GameObject > 3D Object > Capsule

Name it “Laser”, create a material in the material folder and assign it to the capsule to give it a color. Now you’ll want to drag this object from the hierarchy to the prefabs folder under assets. This is now a prefab. You can delete the object in the hierarchy, for as long as we have it in the prefabs folder we’ll be able to access it again.

Once this is done we’ll want to make a variable for the prefab in the Player script so when we’re controlling the player we can have access to the prefab in the script. Now we’ll want to have it accessible in the Unity inspector, but we don’t want it completely public. To have the best of both worlds, we’ll need to add “[Serialize Field]” right above the private prefab variable.

Now that we can see it in the inspector when the player is selected, we’ll want to drag the laser prefab into this box. Now we’ll be able to reach it and do things to it through coding.

Now getting the laser to appear is rather simple. We’ll just want to write an if statement that states “if the space button is hit, then instantiate the prefab.”

It should look something like this:

The problem with just doing this though, is that the laser will always spawn at the location stated in the prefab’s transform position. To make it spawn wherever the player is, we’ll to apply the instantiate command’s 4th way of handling this situation.

So we need to add the player’s position and the rotation of the prefab to the line of code. It should look like this:

Quaternion.identity is what we use when we the rotation to be zero.

Now a capsule object should appear wherever we hit the space key!

Happy coding!

Currently learning to code with the help of GamedevHQ in order to someday my my game ideas come to life!