Coroutine没有等待秒

时间:2016-10-15 13:03:46

标签: c# unity3d

我有两个函数,我希望每隔5秒从Update()函数调用一次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");
        }    
    }

1 个答案:

答案 0 :(得分:0)

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

在coroutine函数结束时将该变量设置为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");
        }
    }
}