【问题标题】:Coroutine not waiting for the seconds协程不等待秒
【发布时间】:2017-02-24 20:11:28
【问题描述】:

我有两个函数,我希望在 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");
        }    
    }

【问题讨论】:

  • 那是因为你的协程在每次更新时都会被调用,等待 5 秒,然后在所有被调用的时候处理协程。尝试使用 InvokeRepeating

标签: c# unity3d


【解决方案1】:

您的协程函数运行正常。问题是您是从 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");
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-11-02
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多