Hi,
I have an animation that is played from the Update() function.
animation.CrossFade(shoot);
yield WaitForSeconds (timeBetweenReloads);
shotsFired++;
Debug.Log(shotsFired);
if (shotsFired >= TOTAL_SHOTS)
{
Debug.Log("out of ammo");
shotsFired = 0;
PlayReload();
}
When this code runs the Debug window shows the variable running from 0 to 5 to out of ammo really fast. I tried to fix this by waiting 2 seconds to increase the value with yield WaitForSeconds(2) but it is not working.
What am I doing wrong?
Would it be better to do this with a timer?
If I understand you correctly, instead of using WaitForSeconds just check if(Time.time > timeBetweenReloads) and perform what you need to do that way.
I’m pretty sure “yield” doesn’t work in Update(). Unity doesn’t want Update() to have to wait for anything.
So if you want a delay between shots, I’d do something like this:
private var b_ready_to_shoot : boolean = true;
function Update() {
if (b_ready_to_shoot) {
doShoot();
}
if (shotsFired >= TOTAL_SHOTS)
{
Debug.Log("out of ammo");
shotsFired = 0;
PlayReload();
}
}
private function doShoot() {
if (shotsFired < TOTAL_SHOTS)
b_ready_to_shoot = false; // Don't shoot until the delay has passed
animation.CrossFade(shoot);
yield WaitForSeconds (timeBetweenReloads);
shotsFired++;
Debug.Log(shotsFired);
b_ready_to_shoot = true; // It's okay to shoot again
}
}
That’s just off the top of my head so it might need some tweaking.
WaitForSeconds() should work just fine. Like pointed out already, the problem is probably how you are using coroutine features (from Update()).
I’m not sure about the coroutine details of unityscript, but in C# you need to do a StartCoroutine() in for example Start() or similar.
Example:
void Start() {
StartCoroutine(Shoot());
}
IEnumerator Shoot() {
while(shotsFired < TOTAL_SHOTS) {
shotsFired++;
yield return new WaitForSeconds(timeBetweenReloads);
// Do something else?
}
Debug.Log("Done shooting");
}