Bullets Won't Stop Shooting When Triggered By Raycast

So, I’m still working on that turret, and I’m still having trouble with the raycast. Every time the raycast is activated, the turret should fire a shot and be done with it. However, once the raycast is activated, it unleashes a plethora of unceasing rapid-fire bullet-storms. Here’s the code I’m using:

#pragma strict

var hit : RaycastHit;
public var rightBullet = gameObject;
var raycastDidHit : boolean = false;

function Update () {
	if(Physics.Raycast(transform.position,transform.right,hit, 4)){
		raycastDidHit = true;
	}
	
	if (raycastDidHit){
	gameObject.SendMessage("shoot");
	raycastDidHit = false;
	}
	
}

function shoot(){
	Instantiate(rightBullet,transform.position,transform.rotation);
}

I know it seems like I should’ve gone with a more streamlined version of the code, like this obvious (For me) first attempt:

#pragma strict

var hit : RaycastHit;
public var rightBullet = gameObject;

function Update () {
if(Physics.Raycast(transform.position,transform.right,hit,4)){
Instantiate(rightBullet,transform.position,transform.rotation);
}

However, this produced the exact same results, so I simply tried a more roundabout way. Which didn’t work.

Where did I go wrong? Whenever I look over the code, it seems to be flawless. Maybe it’s my inexperienced eyes. Maybe it’s something else. I’m just not sure. It’s the first time I’ve used raycasts, so that might be something.

Thanks for the help!

Your problem is, that the code gets called every single frame as long as the ray hits. So instead of shooting 1 bullet per second, you’re shooting more like 60 (dependent on your framerate). A quick fix for your code would be something along the lines of:

var hit : RaycastHit;
var canShoot = true;
var rateOfFire = 0.5; // fire a bullet every 0.5 seconds
public var rightBullet = gameObject;

function Update () 
{
    if(canShoot && Physics.Raycast(transform.position,transform.right,hit,4))
    {
        Instantiate(rightBullet,transform.position,transform.rotation);
        canShoot = false;
        Invoke("EnableShooting", rateOfFire);
}

function EnableShooting()
{
    canShoot = true;
}