Why isn't Yield WaitForSeconds working?

I have created this script:

#pragma strict

var player : Transform;

var playerScript : PlayerScript;

var attackDistance : float = 20;

function Update () {
    var distance = Vector3.Distance (player.position, transform.position);
    if (distance <= attackDistance) {
        Attack ();
    }
}

function Attack () {
    playerScript.health -= 30;
    Debug.Log (playerScript.health);
    yield WaitForSeconds (2);
}

But the yield wait for seconds doesn’t delay the function.

because you need to call ‘StartCoroutine’ with Attack.

Not with UnityScript.

You’re starting a new coroutine every frame where the condition is true. Because there are no instructions after the yield statement, you’re not delaying any kind of action.

If you’re trying to slow down an attack then probably better to store the last time an attack was done and compare to the current time.

1 Like

Can you give an example?

if (Time.time > lastAttackTime + attackInterval)
{
    Attack();
    lastAttackTime = Time.time;
}