Yield Wait for Seconds (A little help here)

Alright so i have the code you can see below and what i want to happen is the enemy attacks the player once and the attack animation plays, then he waits for 10 seconds and then he attacks again and the animation plays again. However, with the below script he attacks all the time and the animation plays all the time too. Any suggestions? Notice that this is just a part of the code. That’s why void Update(){ and other stuff is missing :stuck_out_tongue:

if (readyforattack) {
			if (!inRange ()) {
				chase ();
			} else {
				StartCoroutine(attacking());
			}
		}

IEnumerator attacking(){
		GetComponent<Animation> ().Play (attack.name);
		yield return new WaitForSeconds (10);
		GetComponent<Animation> ().Play (attack.name);
	}

Just a tip, now that you have it working. Declare a WaitForSeconds in your private variables (private WaitForSeconds WFS;), then assign it as a new WaitForSeconds in your start function (WFS = new WaitForSeconds;), this way, you will save memory every time you call yield return new WaitForSeconds in your coroutine, as you can instead call the wait with yield return WFS (or whatever you called it) instead of instantiating a new WaitForSeconds each time.

A little memory optimisation tip for you :slight_smile:

(Compare the two methods in the Unity Profiler if you want to know why this is a good idea)

You are starting multiple instances of the coroutine, one new one every frame, while readyforattack is true. You could try setting readyforattack to false before starting the coroutine and back to true when the coroutine is finished.

if (readyforattack) {
    if (!inRange ()) {
        chase ();
        } else {
            readyforattack = false;
            StartCoroutine(attacking());
        }
    }
}

IEnumerator attacking(){
    GetComponent<Animation> ().Play (attack.name);
    yield return new WaitForSeconds (10);
    GetComponent<Animation> ().Play (attack.name);
    readyforattack = true;
}