Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Why isn't Yield WaitForSeconds working?

Discussion in 'Scripting' started by EliteWalrus, Nov 13, 2014.

  1. EliteWalrus

    EliteWalrus

    Joined:
    Aug 16, 2014
    Posts:
    44
    I have created this script:
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var player : Transform;
    4.  
    5. var playerScript : PlayerScript;
    6.  
    7. var attackDistance : float = 20;
    8.  
    9. function Update () {
    10.     var distance = Vector3.Distance (player.position, transform.position);
    11.     if (distance <= attackDistance) {
    12.         Attack ();
    13.     }
    14. }
    15.  
    16. function Attack () {
    17.     playerScript.health -= 30;
    18.     Debug.Log (playerScript.health);
    19.     yield WaitForSeconds (2);
    20. }
    But the yield wait for seconds doesn't delay the function.
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,377
  3. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    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.
     
    lordofduct likes this.
  4. EliteWalrus

    EliteWalrus

    Joined:
    Aug 16, 2014
    Posts:
    44
    Can you give an example?
     
  5. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Code (csharp):
    1.  
    2. if (Time.time > lastAttackTime + attackInterval)
    3. {
    4.     Attack();
    5.     lastAttackTime = Time.time;
    6. }
    7.