Home and Learn: Games Programming Course
In the last lesson, we got the gun firing and manged to kill a zombie. 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 your MainCamera item in the Hierarchy. Right-click and select UI > Canvas. 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:
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:
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:
If you were to play your game now, you'd see that big white square in the middle of the screen:
You can make that square smaller and turn it into a gunsight.
With your raw image selected in the hierarchy, take a look at the Inspector on the right:
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:
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.)
Drag and drop your image into a Textures folder in Unity (create one for yourself).
With the image selected in your folder, look at the Inspector on the right. For the Texture Type at the top, change it to Sprite (2D and UI). Then click the Apply button at the bottom:
When you click Apply, the image should lose its white background:
Now select the Raw Image item in the Hierarchy. Drag and drop your image from your Textures folder onto the Texture item in the Inspector, under Raw Image. Or you can just click the small circle indicated by the red arrow below. Then select your crosshairs texture:
Don't forget to change the width and height again in the Rect Transform section at the top. We've set ours to 30 x 30. Now test it out. You should have a simple gunsight that allows to you to aim much better than before.
Our image was created in Photoshop. If you wanted to create your own gunsight image, you could use any image editing software that you have. Start with a 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 get the zombie to make a sound, as he's somewhat on the stealthy side, at the moment.
<--Back to the Unity 3D Course Contents Page
Email us: enquiry at homeandlearn.co.uk