协程内部值未正确增加

我是C#和Unity的新手。我试图每5秒将值(计数器)增加1。但是,该值每5秒增加4。当值达到5时,计数器也应该停止。但是,直到我手动停止它,计数器仍会继续增加。


public float energyLevel = 0;

public IEnumerator DoIncrement()
 {
     while (true)
     {
         while ((Math.Abs(Counter - 5) > Mathf.Epsilon)) 
         {
         float duration = 5f; 
         float nTime = 0;
             while (nTime <= 1f)
             {
                 nTime += Time.deltaTime / duration;
                 yield return null;
             }
         Counter++;
         Debug.Log("Counter = " + Counter);
         }
     StopCoroutine(DoIncrement());
     yield return null;
     break;
     }
 }
shilaoban2 回答:协程内部值未正确增加

有一种方法可以创建一个WaitForSecondsRealtime对象,并传递要保留迭代的任何秒数。

例如。

public IEnumerator DoIncrement(){
 int counter = 0;
 while (true)
 {
     yield return new WaitForSecondsRealtime(5f);
     counter += 1; 
 }
}

yield return new WaitForSecondsRealtime(X);
上面的语句将使协程停止执行X秒钟。

计数器+ = 1 计数器++ 每次执行时将加1。

,

替换这些行:

export function async post_return (dataPost)  {
  const response = await fetch(API_URL_REGISTRATION,{
    method: 'POST',body: JSON.stringify(dataPost),headers: {
      'Content-type': 'application/x-www-form-urlencoded'
    }
  });
  
  if (response.ok) {
    return response.json();
  }
  
  // Here you can do some basic error parsing/handling
  throw new Error();
}

一个简单的休息;或产量下降;两者都可以。

您的问题是“ StopCoroutine(DoIncrement())”将递归地对DoIncrement进行新调用,并且您将永远不会停止。 StopCoroutine()不能以这种方式用于迭代器(并且绝对没有必要从内部停止它)。

,

首先,您不必停止内部的协程。到达代码结尾时,它将自动停止。

这是一个可以使用的简单示例:

    private void Awake()
    {
        StartCoroutine(IncrementCoroutine(5,1));
    }

    private IEnumerator IncrementCoroutine(int maxCounter,float timeBetweenIncrement)
    {
        WaitForEndOfFrame endofFrame = new WaitForEndOfFrame();
        int counter = 0;
        float timer = 0;

        while (counter < maxCounter)
        {
            print($"Counter : {counter}");
            while (timer < timeBetweenIncrement)
            {
                timer += Time.deltaTime;
                yield return endofFrame;
            }

            timer = 0;
            counter++;
        }
    }
,

将它包装在while循环中是没有意义的,例如,如果它在结尾处中断,并且在任何地方都没有使用continue

您不需要在协程内部使用StopCoroutine来停止它-只需让该方法返回即可。

您无法保证Counter永远不会接近5的值,因此while循环可能永远不会终止。最好在Counter低于某个数量时循环播放。

我建议您使用WaitForSeconds之类的方法来处理时间,而不要自己做:

private int Counter = 0; // define Counter
public float energyLevel = 0;

public IEnumerator DoIncrement()
 {
     WaitForSeconds waiter = new WaitForSeconds(5f);
     while (Counter < 5) 
     {
         yield return waiter;
         Counter++;
         Debug.Log("Counter = " + Counter);
     }
 }

此外,该问题所包含的信息不足,无法重现您的计数器在5秒钟内多次增加的问题。该部分无法得到充分回答。这可能是因为您一次启动协程4次。

本文链接:https://www.f2er.com/2913532.html

大家都在问