Home and Learn: Games Programming Course

Unity 3D - Player Shooting

In previous lessons, we've created a player and an environment to walk around it. In this lesson, we'll stick a gun in the player's hand and start shooting.


You downloaded a handgun object earlier. If you look in the Project area at the bottom of Unity, you should see a folder called Nokobot. Expand this folder and click on the folder called _Prefabs. Then click on the Handgun Black folder. The second handgun is the one we're going to use. (The first handgun has an animation attached to it. We'll create our own animation shortly.)

In the Hierarchy, expand the First person controller full item. Now drag the handgun onto the First person camera item:

Handgun being dragged onto a first person controller

Positioning your handgun can be quite tricky. But, with your handgun selected in the Hierarchy, change the values in the Inspector to these:


X: 0.12
Y: -0.35
Z: 0.35


X: 5
Y: -4.5
Z: 0


X: 1.8
Y: 1.8
Z: 1.8

Your Inspector should look like this:

Transform values for the handgun

By all means, play around with the position, rotation and scale of your handgun until you're happy with it. You don't have to go with our values. If you can't see your gun, for example, play around with the Position values. And make sure that the Handgun item is a child of First person camera in the Hierarchy.

If you want to see what it looks like, you can have the Scene and Game tabs side-by-side. This makes it easier to see what you're doing and what it looks like when you hit play. To get the Scene and Game screen side-by-side, drag the Game tab onto the Scene view. The red arrow in the image below shows where the Game tab was. It's being dragged to the right:

Reareanging the scene and game views

When you let go of your left mouse button after dragging, it should look like this:

Game and Scene views side-by-side

(You can drag the Game view to the top, above the Scene view, if that works better for you.) Now, when you change the values in the Inspector for the gun, you'll be able to see what that does in the screen on the right.

Now that the player has a gun, let's fire it.


Fire Gun

Click on your Handgun in the Hierarchy to select it. In the Inspector on the right, click the Add Component button at the bottom. Then add an Audio Source:

Adding an audio source to a game object

You now need a decent gunshot sound. Sadly, the Nokobot gun we used doesn't come with any sounds. However, we can go to the Unity Asset store again. Login and go to this page on the store:

Asset Store - Gunshot sounds

Download and import the asset, just like you did with the controller and the gun. You should find that a new folder appears in your Project area. The folder name is Weapons of Choice FREE, and it's by Komposite Sound. Click on the Gun folder to see all the sound files:

Audio files in Unity

If you want to play any of the files to hear what they sound like, select a file and then press the play button at the bottom of the Inspector:

An audio clip component with the Play button highlighted

Once you've chosen your sound, click back on the Handgun in the Hierarchy. Now drag a sound file onto the Audio Clip item:

Dragging an audio file onto an audio source component

Now that we have a gunshot sound, let's write a script to play it.


Gun Fire Script

Click on the Assets folder in the Project area at the bottom of Unity. Inside the Assets folder, right-click and select Create > Folder. Call it Scripts. Inside your new Scripts folder, right-click again and select C# Script from the menu (we've chopped off some items from the bottom of the menu):

Unity menu for creating a new C# script

Type a name for your new script. Call it GunFire. Double-click the script to open it in your coding editor.

We'll need three variables at the top of the code. Add these inside the curly brackets of public class GunFire:

private AudioSource gunshot;
private bool hasGunFired = false;
[SerializeField] float gunFireDelay;

The first two are both private, meaning we don't need to reference them outside of this code. The first is an AudioSource. We've called it gunshot, but you can call it anything you like. The second variable is of type bool (either true or false values). We've called it hasGunFired. It's set to false by default. We'll need this variable to stop the gun firing repeatedly. The third variable is a [SerializeField] one. This means that it will show up in the Unity editor and we can change its value from there. This variable is a float and is called gunFireDelay. You'll be able to set this to half a second, say, or any interval you like.

We placed an Audio Source on the gun, which was the gunshot itself. Let's get that audio source in the Start method. Add this line between the curly brackets of Start:

gunshot = GetComponent<AudioSource>();

Here's what your code should look like:

Unity C# code to get an audio source component

In first person shooter games, guns are fired with the left mouse button. In Unity, keys on your keyboard are mapped for you. The defaults can be found by going to Edit > Project Settings from the menus at the top of Unity. You'll then see this box appear:

The Project Settings dialog box in Unity

Click on Input Manager on the left and you'll see the built-in names you can use for various mouse and keyboard actions. For example, if you wanted to move in the Horizontal direction, the default name to use is Horizontal. Expand the Horizontal item to see the following:

The Input Mnager showing the Horizontal Axis

This is telling you that you can use the inbuilt Name Horizontal in your code:

if (Input.GetButton("Horizontal")) {



Horizontal movement is mapped to not only the mouse but the A and D keys, as well as the left and right arrows.

Now expand the Fire1 option to see this:

The Input Manager showing thw Fire1 button

The Name we can use in an if statement is Fire1. This will be mapped to mouse 0, which is the left mouse button.

With that in mind, go back to your code. Enter the following if statement in between the curly brackets of Update:

if (Input.GetButtonDown("Fire1"))

So, if the button that was held down has the Name Fire1, which is taken from the project settings you've just seen, then do something. (Note: the Name has to go between two double quotes.)

What we want to do is check that bool variable we set up. If hasGunFired is false, it means it's ready to fire. To check the bool variable hasGunFired, we need another if statement. Add this if statement between the curly brackets of the one you already have:

if (hasGunFired == false)

Now, in between these curly brackets, we can do something. The something we need to do is to start a coroutine. This acts as a sort of timer. The timer will be set to whatever value is in our gunFireDelay variable.

Before adding the coroutine, your code should look like this (the new code is highlighted):

Unity C# code showing how to detect when the left mouse button is pressed

Now add this line between the curly brackets of the inner if statement:


If that's not clear, it should be this:

if (Input.GetButtonDown("Fire1"))

if (hasGunFired == false)




You'll get red underlined for FireGun(). That's because FireGun is the name of the coroutine we want to start. We haven't written this yet. But FireGun is just like a method name - you can call it almost anything you want. Doesn't have to be FireGun.

Anyway, outside of the Update curly brackets, add this:

IEnumerator FireGun()

hasGunFired = true;
yield return new WaitForSeconds(gunFireDelay);
hasGunFired = false;


An IEnumerator is part of the Collections library in C#. (It's something called an interface.) But the effect is it allows you to set a pause before resuming. It does that with this line:

yield return new WaitForSeconds(gunFireDelay);

The IEnumerator will pause for however long the value of gunFireDelay is.

Notice what else we're doing here, first we set the bool variable hasGunFired to true. This disables the gun so you can't shoot. Then we play the gunshot sound. After the delay, we set hasGunFired back to false. In other words, disable the gun, play a sound, wait for a while, then enable the gun.

But your code should look like this (new lines are highlighted):

Unity C# code showing how to fire a gun

OK, save your code and go back to Unity. Now drag and drop your script onto the Gun in the Hierarchy:

Dragging the C# script onto a gun game object in teh Hierarchy

Select your gun and take a look at the Inspector. The script should be there:

The gun script attached to a game object in the Inspector

Notice that our gunFireDelay variable is there. The default is 0. You need to change this. Try a value of 0.25.

Now play your game. Make sure to turn the sound up on your computer.

One problem you will have noticed is that the gun fires immediately, even though you haven't clicked your left mouse button. This is due to a setting on the Audio Source. So, stop your game and go back to Scene view. Click on your Handgun in the Hierarchy. In the Inspector, expand the Audio Source component. Now uncheck Play On Awake:

The Play On Awake item highlighted for an audio source

Try it again. Now, you won't hear the gunshot when the game loads. You should be able to walk around and shoot, as shown in the short video below:




One thing you may have noticed when playing the game is the shadows cast by the capsule. It might have looked like this:

A shadow cast by a capsule in Unity

You can switch shadows off. To do so, select the Capsule mesh item in the Hierarchy:

The Capsule Mesh highlighted in the Hierarchy

With the Capsule mesh selected, have a look at the Inspector on the right. Expand the Mesh Renderer item and notice that it has a Lighting section:

The Mesh Renderer and Cast Shadows items highlighted int the Inspector

Select Off in the dropdown for Cast Shadows. When you play your game, the capsule's shadow should be gone.

However, you may see shadows for the gun. If you don't like this, you can switch then off. Unfortunately, you need to switch off the shadows for all the gun parts, too. To do this, select your gun in the Hierarchy. Now expand the M1911 Handgun_Model item:

The Handgun item highlighted in the Hierarchy

In the Inspector, switch off the shadows, just like you did for the Capsule mesh.

You're not done yet, though. There are a few more parts of the gun that will cast shadows. You need to turn them off for the following:

Casing Exit
M1911 Magazine (Expand Magazine_Location > M1911_Magazine Black)

Test your game out to see if all the shadows are gone.

OK, now that you can shoot at things, let's add a gun sight. We'll do that in the next lesson below.

<--Back to the Unity 3D Course Contents Page

Email us: enquiry at homeandlearn.co.uk