简体   繁体   中英

Coroutine not waiting for the seconds

I have two functions , I want harmPlayer() should be called after every 5 seconds from Update() function. But the it is getting executed several hundred times from update() functions. I understand the Update() function is getting executed on each frame and is calling everytime the harmPlayer(), then how can i implement wait for 5 seconds'

 IEnumerator HarmPlayer()
    {
        Debug.Log("Inside Harm Player");
        yield return new WaitForSeconds(5);
        Debug.Log("Player Health is the issue");

    }

Here is my Update() function

void Update () {

        transform.LookAt(target);
        float step = speed * Time.deltaTime;
        distance = (transform.position - target.position).magnitude;
        if (distance < 3.5)
        {
           animator.SetFloat("Attack", 0.2f);
            StartCoroutine("HarmPlayer");
        }    
    }

Your coroutine functions is working properly. The problem is that you are calling it from the Update function and it's being called many times in a second. You can use a boolean variable to check if the coroutine function is running. If it is running, don't attack or start new coroutine. If it is not, then you can start coroutine.

At the end of the coroutine function set that variable to false . There other ways to do this but this seems to be the easiest way.

bool isAttackingPlayer = false;
IEnumerator HarmPlayer()
{
    Debug.Log("Inside Harm Player");
    yield return new WaitForSeconds(5);
    Debug.Log("Player Health is the issue");
    isAttackingPlayer = false; //Done attacking. Set to false
}

void Update()
{

    transform.LookAt(target);
    float step = speed * Time.deltaTime;
    distance = (transform.position - target.position).magnitude;
    if (distance < 3.5)
    {
        if (isAttackingPlayer == false)
        {
            isAttackingPlayer = true; //Is attacking to true
            animator.SetFloat("Attack", 0.2f);
            StartCoroutine("HarmPlayer");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM