- Home /
Yield WaitForSeconds Not Working. Coroutine.
Hey guys. I'm currently developing a First Person Shooter and I've made this code for a rapid-fire Uzi. However, when I tried to slow down the rate of fire using the WaitForSeconds command, nothing happened. Please help!
I've made two different scripts one for shooting and one for sound. Here's the firing script.
#pragma strict
var Effect : Transform;
var TheDammage = 100;
function Update(){
if (Input.GetMouseButton(0)) {StartCoroutine(Fire());}
}
function Fire () {
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 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);
}
yield WaitForSeconds(0.1);
Update();
}
And the sound script.
@script RequireComponent(AudioSource)
var front : AudioClip;
var back: AudioClip;
function Update(){
if (Input.GetMouseButton(0)) {StartCoroutine(Fire());}
}
function Fire(){
audio.PlayOneShot(front, 1.0);
yield WaitForSeconds(0.1);
Update();
}
Thanks that worked. I can't believe that flew right by my head.
Answer by rutter · Aug 07, 2014 at 05:14 AM
Coroutines aren't exclusive. If you call Fire()
50 times, you'll end up with 50 independent calls to Fire
, all running simultaneously. Each of them will wait 0.1 seconds.
You usually shouldn't call Update
manually -- the whole point of the function is that Unity calls it for you, once per frame.
You might instead have Fire
manage a bool (say, readyToFire
). As soon as the coroutine starts, it can set readyToFire
to false; after it's done waiting, it can set it back to true. Meanwhile, Update
would only call Fire
if the user is pressing a key and readyToFire
is true.