- Home /
Limiting the time my gun can shoot
I am trying to limit the rate of fire for my gun. I use this script:
function Update ()
{
machineflash = GameObject.FindWithTag("machineflash");
// raycast settings
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
var localOffset = transform.position;
// check to see if user has clicked
if(Input.GetButton("Fire1"))
{
{
// if so, did we hit anything?
if (Physics.Raycast (localOffset, direction, hit, 400))
{
// just so we can see the raycast
Debug.DrawLine (localOffset, hit.point, Color.cyan);
// print to console to see if we have fired
print("we have fired!");
// send damage report to object
hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
}
AudioSource.PlayClipAtPoint(gunshot,transform.position);
Instantiate (muzzleflash, machineflash.transform.position, transform.rotation);
}
}
But whenever I try to put a WaitForSeconds, it says that function Update() cannot be a coroutine. How can I fix this.
Answer by homeros · May 27, 2011 at 07:57 AM
You can use a boolean to prevent fire and set it outside of Update in a coroutine.
if(Input.GetButton("Fire1") && !gunFired)
{
StartCoroutine(GunFire());
}
use this outside of Update
function GunFire()
{
gunFired = true;
yield WaitForSeconds(1);
gunFired = false;
}
Assets/Player/machinegun.js(16,41): BCE0005: $$anonymous$$ identifier: 'gunFired'.
var gunFired : bool = false;
use this on top of your code as a field.
I don't exactly know which one you meant by first part but i'll list everything.
-put "var gunFired : bool = false;" on top of your code, outside of every function.
-replace "if(Input.GetButton("Fire1"))" with "if(Input.GetButton("Fire1") && !gunFired)"
-put "StartCoroutine(GunFire());" on the first line inside if statement
-put function GunFire() { gunFired = true; yield WaitForSeconds(1); gunFired = false; }
anywhere outside of Update function.
Thanks mate, works like a charm. It was more complicated than anything I could have figured out.