Setting up ‘Pew Pew Pew’ … with C# in Unity
With this article I am going to continue with my build of a space shooter game and set up the laser for my player object.
First we set up the object that will represent the laser in game, a 3D capsule and naming it Laser. We then create a prefab of the Laser by dragging it from the Hierarchy to the Prefabs folder and then remove if from the Hierarchy altogether. You will be left with the Laser only as a Prefab.
In the scripts folder of the Project panel we create a new C# script and call it Laser as well. Then, open that script in your editor. This is going to be a basic script just to get the laser defined as a GameObject and to define its speed when used in the game. That script looks like this…
Next we want to add the Laser tot he Player, since the Player will be the object using it. We open the Player C# script and add the Laser prefab as a GameObject variable and then add where it is spawned when the Space key is pressed. Space is being defined as the fire button for the game. This is added to the Player script like this…
Next, we need to link the laser to the player in Unity. This is a process of dragging and dropping the appropriate scripts and objects onto one another. I’ll list what goes on, it’ll seem a little harry at first.
- Drag the Laser script onto the Laser prefab to link the two.
- Click on the Laser prefab and drag it into the Inspector and onto the field labeled Laser Prefab in the area where the Laser Script is shown. This links the Laser prefab as the GameObject that the Laser Script is declaring as its variable.
- Select the Player prefab and drag the Laser prefab into the Inspector and onto the field labeled Laser Prefab in the area where the Player Script is shown, same as you did for the Laser Prefab itself. This links the Laser prefab to the Player which also declares the Laser prefab as a GameObject variable.
Once you have done this, you can play the game, tweak the serialized variables in the inspector, and get something like what I shown at the beginning of this tutorial. The Player is now set up with a means to fire on its enemies. In the next article I will go into more detail about the process of spawning, or instantiating, GameObjects.