Projectile Script Problems.

I have a number of problems with this script. If anyone can help on anyone of them, it would be greatly appreciated.

  1. The script wont halt the shooting, which is what the wait() function is for.
  2. The script shoots at random every which way, I don’t know why
  3. The script creates tons of the object when held down

The script:

var projectile : Rigidbody;
var speed = 20;
var fire : boolean = false;
var pressed = 0;

function Update () {
if(Input.GetKey(KeyCode.F) && (pressed == 1)) {

clone = Instantiate(projectile, transform.position, transform.rotation);
clone.velocity = transform.TransformDirection( Vector3 (0, 0, speed));

Destroy (clone.gameObject, 3);
Debug.Log("Reloading");

wait();

Debug.Log("Ready to Fire!");
pressed = 0;

}

if(Input.GetKey(KeyCode.F)) {

pressed = 1;
Debug.Log("Pressed E");

}

}

function wait() {

yield WaitForSeconds (5);

}

There are several ways to get your gun to wait. The easiest from here would be to use your wait function to set a flag:

function wait() {
   canFire = false;
   yield WaitForSeconds (5);
   canFire = true;
}

And then in your firing code:

if(Input.GetKey(KeyCode.F) && (pressed == 1) && canFire) {

And to get it to go in the right direction try:

clone.AddForce(transform.forward * 1000);

As for tons of clone objects, by waiting you will have less. You can add code to each bullet so that it is destroyed after a certain amount of time. Or you can implement a pooling system so that bullets are reused. Actually if you can only fire once every 5 seconds, you can just reuse the bullet. If you do, be sure to set the velocity and angular velocity to 0 before adding the new force.