簡體   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