繁体   English   中英

协程不等待秒

[英]Coroutine not waiting for the seconds

我有两个函数,我希望从Update()函数每隔5秒调用一次harmPlayer()。 但是,它已从update()函数执行了数百次。 我知道Update()函数在每个帧上都会执行,并且每次harmPlayer()都会调用,那么我如何实现等待5秒钟呢?

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

    }

这是我的Update()函数

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");
        }    
    }

您的协程功能正常运行。 问题是您是从Update函数调用它的,在一秒钟内被多次调用。 您可以使用boolean变量来检查协程函数是否正在运行。 如果它正在运行,请不要攻击或启动新的协程。 如果不是,则可以启动协程。

在协程函数的末尾,将该变量设置为false 还有其他方法可以做到这一点,但这似乎是最简单的方法。

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");
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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