How to Fix a Guns Firing Script so it Doesn't Constantly Fire

(Edited question)

Hello everyone! I’m in the process of making a shotgun script where you’re supposed to be able to fire a raycast every 1 or so seconds, and the animation is about that long as well, but I’m not sure how to delay the shooting otherwise you can shoot constantly and with infinite ammunition. I would like to have two shots, and when you shoot two, you have to reload, otherwise you hit ‘r’, and it reloads the gun then as well.

Thanks,
Henry

private var AmmoInGun : int = 2;

var Effect : Transform;
var TheDammage = 100;
var Distance = 50;
var Gun : Transform;

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

		}
	
	}
	
		if(AmmoInGun == 0)
		{
			Reload();
		}	
}

function Shoot()
{
		audio.Play();
		Gun.animation.CrossFade("Shoot");
		AmmoInGun -= 1;

}

function Reload()
{
			Gun.animation.CrossFade("RELOAD");
	
}

you could either move the weapon logic to a coroutine:

while (true)
{
while (!Input.getButtonDown("Fire"))
  yield return new WaitForEndOfFrame();

shoot()

yield return new WaitForSeconds(3.1f)
}

or you could add a reload counter to your script:

public float reload;

void Update()
{
  reload -= Time.deltaTime;

  if (reload < 0 && Input.GetButtonDown("Fire"))
  {
    Shoot();
    reload = 3.1f;
  }
}

Not to be short with you but coroutine’s would do that for you.

Here is link about them.

I’m onMy phone. Can you tell. :wink:

public float cooldown = 1f;
float cooldownRemaining = 0;

void Update
{
cooldownRemaining -= Time.deltaTime;
	if(Input.GetMouseButton(0) && cooldownRemaining <= 0)
{
*whatever it is you want to do upon fire here*
cooldownRemaining = cooldown;
}
}

This will create a cooldown, and then add the cooldown to a timer for the gun. You can change the “cooldown” variable to be any amount you want; it will be in seconds.

This is obviously the best I can do without seeing your script; and is written in C#, not Javascript, although the principle is the same.