Home / Legacy / Lesson 2: Create the First Person Weapon

Lesson 2: Create the First Person Weapon

/
/
/
1845 Views
This entry is part 4 of 15 in the series Unity 3d Fundamentals Course

In this lesson we will create the First Person Weapon Setup. The goal at the end of the lesson is to have the 3d model in place and being able to equip the weapon at runtime using a Trigger.

This is the second lesson of the Unity 3d Fundamentals Course. We will continue with the project created on the first lesson. Check here.

Lesson Outline

Import the First Person Controller

We will begin by importing the First Person Controller into our scene. Unity already has a first-person controller that we ca use in our games, so we will just use that and later modify it to our needs.

If you are working with Unity 4.3.3 or above you may prefer to use the new Unity Sample Assets available on the Unity Store. The new First Person Controller is lot more complete.

Unity works with Packages to import and export assets between projects. Packages are the best way to move or share assets between different projects. When we want to export something out of our project, we need to create a new package to ensure that all references to our object are stored and later maintained when being imported.

Unity Packages are needed when working with “virtual” entities in the Unity Editor such as Scenes, GameObjects or Prefabs. If we only need to export a Texture or an Audio File, for example, we can just import it to the new project without creating a package for it.

To import a new package we need to open the Assets menu and choose Import Package. On this submenu we have the option to import Custom Packages, useful to import packages stored on our computer, or we can just import one of the packages already bundled with the Unity Installation. In this case we will import the Character Controller Package.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

It will open a window with all the assets to import. By default all assets are selected so we just need to press Import. The first time you import one of the default packages it will create a new Standard Assets folder.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

To import the Character Controller into the scene expand the folder Character Controllers and just drag the First Person Controller Prefab (we will talk about Prefabs later) into the Hierarchy or the Scene View.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Position the Controller on the terrain making sure that it is above the terrain surface, otherwise it will fall through the surface.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

 

Import the Weapons Pack from the Asset Store

Modern Weapons Pack
Modern Weapons Pack

First we will import the weapons from the Asset Store. I chose the Modern Weapons Pack by 7XFGames because as you will see it has awesome weapons available. Thanks 7XFGames.

You need to have Unity 4.3.4 or above to use this package.

After downloading and importing the package from the store, you will have a new folder on your Project View called Modern Weapons Pack. If you expand this folder you can see all the available weapons.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Place the Weapon on the Scene

First, select one of the weapons. In my case I will choose the classic AK-47. To import the weapon into the scene expand the folder FBX and just drag the AK-47.FBX file into the Hierarchy or the Scene View.

Change to Layout 2 by 3 to see the Scene and Game View at the same time.

The weapon needs to follow the player camera to give the illusion that the player is holding it. So we need to parent the weapon to Main Camera on the First Person Controller.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Now that the weapon is in place, you can see that the model is being cut off near the edges of the screen. To solve this you need to change the Near Clip Plane of the Player Camera to 0.01 which is the smallest value allowed.

The camera clip planes define where the camera frustum starts – Near Clip Plane – and ends – Far Clip Plane. Everything that is outside these values is not rendered. So in this case the weapon is being cut off because it is closer to the Player than the default distance of the near clip plane (0.3).

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Create a Player Weapons Controller

Although we already have the weapon in place, we need to remember that the player will start without weapons. The weapon will only be available after being picked up. So we will disable the weapon in order to hide it.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

We will need to enable the weapon at runtime so we will create a PlayerWeaponsController.cs to manage all weapon related events.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

This controller will be quite simple because we are only dealing with one weapon. Later we will improve it in order to manage switching between multiple weapons.

</> PlayerWeaponsController.cs

We will start by creating a public method to equip the weapon. For now this method will take no arguments because we only have one weapon to deal with.

To enable the weapon we will need a reference to the Weapon GameObject so we will create a public GameObject variable to hold our weapon.

In order to equip our weapon we will just activate the Weapon GameObject.

Now we are able to pick up the weapon at runtime and show it on the screen. You Player Weapons Controller should look like this:

Add a crosshair

We will add two different crosshairs to our game. We will need a default crosshair that will be will be visible when the player is not carrying any weapon. As soon as he equips the weapon the crosshair must change to the other one to reflect the weapon.

There are several ways to do this but the simplest, in my opinion, is by using a GUITexture.

  • With a GUITexture we can easily display any texture on the screen;
  • Since it is a component it can be applied to a GameObject and toggled at runtime;

A GUITexture is a component that displays a texture on the GUI Space. It is important to keep in mind that the positioning values are measured in Screen Coordinates and not World Coordinates.

First we will create a new GUITexture.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Then we need to assign our GUITexture image. Drag the Texture File into the Texture Slot of just use the browse function.

 

crosshair
Default Crosshair
crosshair_weapon
Weapon Crosshair

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

By default the GUITexture position is already on the middle of the screen. So we just need to adjust the texture size and pixel inset – to keep the image in the middle of the screen, the inset is always equal to minus the half width and height.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

This will be the default crosshair and it will be enabled from the beginning of the game. Now we need to add a crosshair for the weapon. This second crosshair will be enabled at runtime, as soon as the player equips the weapon.

We will use the Player Weapons Controller to assign the new image to the GUITexture when the EquipWeapon method is called. We need a reference to our weapon crosshair image and another one crosshair GUITexture component.

Next we will modify the EquipWeapon method to change the crosshair texture to the weapon crosshair as soon as the method is called.

Your Player Weapons Controller should look like this:

Bring it all together

Now that we have everything ready we need to apply our Player Weapons Controller script and assign all the necessary references.

To apply the Player Weapons Controller script to the First Person Controller GameObject just drag it onto the GameObject or use the Add Component button on the Inspector.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

To assign the necessary references, just drag each GameObject to the corresponding slot on the Player Weapons Controller Inspector View.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

 

Test our scene

Right now we have a weapon in place and ready to be enabled.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup
Mailman

However we cannot test our code in runtime. One solution would be to create an Input command on our code to enable the weapon during Play Mode. This is a quick and easy solution. However we are adding unnecessary code to our scripts.

I found this Editor Extension on the Asset Store called Mailman by Nick Gravelyn. It is a very simple extension but it solves this testing problem without the additional code.

Nicks’ description about his extension explains clearly what it does:

“Mailman is a simple Unity editor extension that allows you to manually send or broadcast messages to any game objects in the scene while the game is running. This is great for testing your components’ behavior or interacting with your game to try out new things. Simply open the window, enter the message name, optionally provide an argument, and click Send. That’s it! “

So we are going to import the Mailman into our project and use it to test our Player Weapons Controller at runtime. After importing the Maiman into our project we will have a new window available on the Window Menu.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

The Mailman window is just like any other window in our editor so we may leave it floating over the interface or just dock into another tab. In this case I chose to dock the window into our Inspector View Bottom.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

The Mailman only works in Play Mode. So we are going to disable our weapon GameObject and enter Play Mode. To test our script we just need to select the First Person Controller GameObject – you always need to select the GameObject that is holding the script you want to test – and write the method name we want to test and press Send Message.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Pick up the Weapon

Our Player Weapons Controller is working properly. Now we need a way to pick up our weapon at runtime. We are going to use Triggers in order to implement this functionality.

So what is a Trigger?

A Trigger is just a Collider with the trigger property enabled.

But what is a Collider?

A Collider is a component that allows GameObjects to detect collisions. For example if you want to put a wall in your scene to block the player movement, you need to add a Collider to the wall, otherwise the player will just pass through the mesh like if it is not there.

…and back to the Trigger…

So, the Trigger is a collider that instead of blocking the objects movement, it triggers events about the collision allowing us to do something about it.

In this case we want to detect when the player is near the weapon so that he can grab it. First we are going to need a weapon for the player to grab. We need to create a new copy of the weapon and place it somewhere in our scene.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Next, we are going to create a trigger for the new weapon. The best way to create Triggers is to start with a Primitive Cube because it has already the Box Collider and while placing it on the scene you can see it perfectly. So, create a Cube and place it where we want our trigger to be.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

 

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Then in order to use the Cube as a trigger we need to disable the Mesh Renderer, to make the cube invisible and enable the isTrigger property of the Box Collider so that it can detect the collision events without blocking the player movement.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

Now that the trigger is in place we need a script to deal with the collision events that will be sent by the trigger. So we are going to create a TriggerWeapon.cs to listen to those events and perform actions upon receiving them.

</> TriggerWeapon.cs

The Trigger Weapon script will be responsible for catching the events sent by the Trigger component. When using a Trigger we have three events to listen for:

OnTriggerEnter

OnTriggerStay

 

OnTriggerExit

All these events have a parameter other of type Collider. The other is a reference to the Collider that is triggering the events. One possible use of this parameter is to check if it was the player entering the Trigger. For example you could have a door in your game that is activated by the player but not by the enemies. So with this parameter you could check whether the object that just triggered the event is the player and open the door only in that case.

In this example we will be using only the OnTriggerEnter event because we want the player to grab the weapon as soon as he enters the Trigger. We need to destroy the weapon that was on the ground to make it disappear and then enable the one that is hidden on the “hands” of the player.

We will start by adding a reference to the weapon GameObject.

Then we need to edit the body of our OnTriggerEnter method in order to destroy it.

Next we need to call the method EquipWeapon of the Player Weapons Controller script. We could just make a reference to this component but since is the player that is holding the script we will find it during runtime. One way to find GameObjects at runtime is by using Tags.

We need to check if our First Person Controller has already the tag Player assigned.

Unity 3d Fundamentals Series Lesson 2 Create the First Person Weapon Setup

This method returns the GameObject we are looking for. But in this case we want to access the Player Weapons Controller script, so we also need to use the GetComponent method. This method allows us to access any component applied to the GameObject where it is called.

With access to the component we can finally call the necessary method EquipWeapon.
Our Trigger Script is now completed and it should look like this.
To finish we just need to add this script to our Trigger GameObject and assign the proper public references, in this case the weapon that is on the ground. By now this should be pretty easy to accomplish so no images are needed.

With everything in place we are ready to test our scene without requiring the Mailman component. Just press play and when moving to the weapon you should instantly grab it.

What’s next…

On the next lesson we are going to create our environment importing all the necessary 3d models and textures into our project.

Series Navigation<< Lesson 1: Working with the Unity TerrainLesson 3: Prefabs and Unity 3d Physics >>
  • Facebook
  • Twitter
  • Google+
  • Linkedin
  • Pinterest
  • Reddit

18 Comments

  1. Hi
    Brilliant work, thank you very much . It helped a lot to understand the mechanism of the unity.
    Please check out my code for Unity 5 because yours didn’t work to me. Please fell free to delete my comment if you find the modified code wrong.
    TriggerWeapon.csusing UnityEngine;
    using System.Collections;

    public class TriggerWeapon : MonoBehaviour
    {

    public GameObject weapon; // Reference to the weapon that is going to disappear

    // Event that is triggered when an object enters the collision box
    // The object that enters the collision is the one passed as the “other”
    // This event is only triggered once
    void OnTriggerEnter (Collider other)
    {
    // Find the Player by using the tag “Player”
    // Gets the Component PlayerWeaponController on the Player
    // Calls the public method to equip the weapon
    GameObject.FindWithTag(“Player”).GetComponent().EquipWeapon();

    Destroy (weapon); // Destroy the weapon we just catch
    }
    }

    • Hey, I’m glad it was useful to you. Thanks for the modified code. It seems that the method FindGameObjectWithTag was changed to FindWithTag on Unity 5. As soon as I try the new version I will have to correct some of these modifications. But its a start. Thanks

  2. What drugs are you on that ever made you think this would work.

    GameObject.FindGameObjectWithTag (“Player”).GetComponent ().EquipWeapon ();
    I want to know so I can get some for myself.

  3. I am new to Unity, I was wondering if you could show how to add the Modern weapons pack sights to the gun from 7xfGames? I know how to add the gun and link it to the player but to use the ACOG sight it doesn’t work, so I was wondering if you could show explain, and thank you in advance.. Excellent post

  4. get error

    Assets/scripts/TriggerWeapon.cs(17,61): error CS0411: The type arguments for method `UnityEngine.GameObject.GetComponent()’ cannot be inferred from the usage. Try specifying the type arguments explicitly

    • tanx but dont work
      Assets/scripts/TriggerWeapon.cs(18,61): error CS0411: The type arguments for method `UnityEngine.GameObject.GetComponent()’ cannot be inferred from the usage. Try specifying the type arguments explicitly

      • and i use this code:
        GameObject.FindGameObjectWithTag (“Player”).GetComponent ().EquipWeapon ();

        dont error but dont work

  5. sorry this work whit this code
    GameObject.FindGameObjectWithTag (“Player”).GetComponent ().EquipWeapon ();

    great tutorial tanx

  6. I can’t seem to get the GUI UI working
    I create an empty and added a rendering component (GUI texture) select the crosshair and it will not show up.

Leave a Comment

Your email address will not be published. Required fields are marked *