Adding a Gun Sight

In the last lesson, we got the gun firing and added a nice audio sound. It would be nice, though, if we had a sight for the gun, so we could see where we're aiming. You can add a sight quite easily by using the canvas.

Select the First person camera item in the Hierarchy. Right-click and select UI > Canvas:

Unity UI, Canvas menu

You will then have a canvas item under the camera, as well as an Event System item at the bottom. Rename the Canvas to GunSight:

A Canvas item in the Hiearachy

With the GunSight canvas highlighted in the Hierarchy, right-click again. From the menu, select UI again. This time, select Raw Image from the sub menu. A Raw Image item will be added under your GunSight canvas:

A Raw Image item selected in the Hiearachy

With the Raw Image item selected (you can rename it, if you want), take a look at the Scene view. You'll see that your raw image is a white square in the middle:

The canavs displayed in Scene view

If you were to play your game now, you'd see a that big white square in the middle of the screen:

Game view showing an oversized gun sight

You're probably asking yourself, Can I make that square smaller and turn it into a gunsight? Well, yes you can.

With your raw image selected in the hierarchy, take a look at the Inspector on the right.

Changing the height and width of a raw image via the Inspector

Change the Width and Height values under the Rect Transform section. We've changed ours from the default 100 to 10 for each. It looks like this, when the game is played:

Game view showing a white raw image used as a gunsight

Change the width and height to something smaller, if you think 10 is too big.

You can add a texture to your raw image, to get a better gunsight. This will replace the white square with whatever your texture image is. Let's see how it works. Download the image below: (Right-click, Save Image As.)

A gun sight image for download

Drag and drop your image into the Textures folder in Unity. Now select the Raw Image item in the Hierarchy. Drag and drop your image onto the Texture item of your Raw Image:

Dragging and dropping a texture to use as gun sight

Don't forget to change the width and height again, in the Rect Transform section at the top. 15 x 15 seem OK. Then test it out.

Our image was created in Photoshop. If you wanted to create your own gunsight image, you can use any image editing software that you have. Start with transparent background. A size of 300 by 300 works well. Now create something to use as a gunsight. Save the file as a PNG image, as these are OK with transparency. Drag and drop your new image into Unity.

 

In the next lesson, we'll try our hand at animation, as we add some recoil to the gun.

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