Need help with fire rate on raycast shooting script. Please Help.

I’ve been trying to get this script to shoot then wait before shooting again.
When I use this script:

#pragma strict

var Effect : Transform;
var TheDammage = 100;

function Update () {
	
	var hit : RaycastHit;
	var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0));
	
	if (Input.GetMouseButton(0))
	{
		if (Physics.Raycast (ray, hit, 100))
		{
			var particleClone = Instantiate(Effect, hit.point, Quaternion.LookRotation(hit.normal));
			Destroy(particleClone.gameObject, 2);
			hit.transform.SendMessage("ApplyDammage", TheDammage, SendMessageOptions.DontRequireReceiver);
		}
	}
	
}

It just repeats the script pretty quickly. I’ve tried putting “yield WaitForSeconds (0.05);” at the end of the script but when I try that it just doesn’t shoot anymore. Can someone please help me? It’d be much appreciated.

Your input checking says “Is the left mouse button down? If so, shoot.” So, EVERY call to Update where the mouse button is down, it shoots. If you’d like a delay between shots, you’ll have to keep up with the elapsed time since the last shot. I also recommend driving the time delay by a variable. Something like:

public float timeDelayBetweenShots = 0.5f;

private float timeSinceLastShot = 0.0f;
private bool canShoot  = true;

// in your update function
if(canShoot)
{
    if (Input.GetMouseButton(0))
    { 
        // Start the shooting state tracking.
        timeSinceLastShot = 0.0f;
        canShoot = false;
        // Your raycast hit-test stuff here
    }
}
// Else we are shooting, so keep track of the delay.
else
{
    timeSinceLastShot += Time.deltaTime;
    
    // If enough time has passed, we can shoot again.
    if(timeSinceLastShot >= timeDelayBetweenShots)
        canShoot = true;
}
  • Eck