4. Add the following variable:
var projectile : GameObject; // the object to instantiate
The variable is of type GameObject, because you’ll eventually need access to more than just its transforms.
5. In the Update function, add the following:
if (Input.GetButton ("Fire1")) { // if the Fire1 button (default is ctrl) is pressed
Activate(); // do whatever the fire button controls
}
The code starts in the Update function, because the engine needs to constantly check to see if the player has
pressed the fire button. You’ve used several virtual buttons for navigating already. If you check the Input Manager
(Edit ➤ Project Settings ➤ Input), you will see that the left Ctrl key and mouse button 0 (the left button) are mapped
to “fire1.” Because you are using the left mouse button for picking, you will need to remove the left mouse option from
the Input manager.
6. From the Edit menu, select Project Settings and choose Input.
7. Open Fire1 and delete mouse 0.
8. Create a function to handle the action:
function Activate () {
// create a clone of the projectile at the location & orientation of the script's parent
var clone : GameObject = Instantiate (projectile, transform.position, transform.rotation);
}
This line creates a variable named clone, of type GameObject, and Instantiates, or creates a new copy of the object
you will load into the projectile variable. And it does it at the location and orientation of the object this script is sitting on,
transform.position and transform.rotation. It won’t go anywhere yet, but the specified gameObject will be created.
You are probably wondering why you don’t just put the Instantiate code directly into the if clause in the Update
function. At this early stage, you certainly could. But later on, you will discover that you will require more control.
A ray gun might need to be active as long as the fire button or key is pressed, but a large projectile such as the
cannonball should be forced to never fire more than a certain number per second. The player will just mash the key or
button down, so you will have to do the checking. Another scenario is a flashlight, where the light is toggled on and off
the first time the button or key down happens.
9. Save the script.
Next, you have to decide where to put the new script. You could put it directly on the First Person Controller, but
that would make it hard to position, so, instead, you will create a parent object to hold any gear your player may need
to handle. Because the aim is a requirement, the holder object will have to be parented to the Main Camera.
1. Select the main camera and Focus in on it.
2. Create an empty gameObject and name it Gear Handler.
3. Drag it onto the main camera.
4. Now create a proxy weapon from a cube to give the projectile a place to be
instantiated from.
5. Name it Proxy Weapon and scale it to about 0.15×0.15×1.
6. Disable its Box Collider.