【问题标题】:StopCoroutine not working not even StartCoroutine(string), StopCoroutine(string) in unity3d在 unity3d 中,StopCoroutine 甚至 StartCoroutine(string)、StopCoroutine(string) 都不起作用
【发布时间】:2013-11-13 07:25:26
【问题描述】:

我不明白为什么。

我已经阅读了很多关于它的文档,并且有很多 cmets

StopCoroutine(string) 只能停止以 StartCoroutine(string) 开头的协程

代码如下。

在 CharTouchControl.cpp 类中

if( Input.GetKeyDown( KeyCode.Q ) )
{
    _CharControl.StartCoroutine("useFever", 10);
}

_CharControl 是 CharTouchControl 的成员,当然 _CharControl 引用了下面的 CharControl 实例。

和 InClass CharControl

public IEnumerator useFever(float _duration = 10)
{
    if( m_nUseFever < _nFeverMax )
    {
        Debug.Log("Stop!!");
        StopCoroutine("useFever");
        yield return new WaitForEndOfFrame();
    }

    m_fgCharState = CharState._FEVER;

    // fever particle
    m_psFeverPaticle.Simulate(4);

    yield return new WaitForEndOfFrame();
} // end of useFever

当 m_nUseFever

但协程不会停止并模拟颗粒。

有人帮忙吗?

【问题讨论】:

  • 只是出于好奇,你为什么在协程内部使用StopCoroutine?在第一个if 语句中使用yield break
  • 您调用StopCoroutine,这会阻止函数的其余部分(包括粒子模拟)执行。你想达到什么目的?

标签: unity3d coroutine


【解决方案1】:

正如 Jerdak 提到的,你应该在 Coroutine 中使用 yield break。 协程完成其代码块后将自动停止。使用yield break,应该将其发送到代码块的末尾。

此外,您可以修改代码,使其仅在条件为真时运行代码块。我在下面的例子中做到了这一点。如果条件为假,协程将等待帧结束然后退出。

public IEnumerator useFever()
{
    if( m_nUseFever > _nFeverMax )
    {
        m_fgCharState = CharState._FEVER;

        // fever particle
        m_psFeverPaticle.Simulate(4);
    }

    yield return new WaitForEndOfFrame();        
} //Coroutine automatically exits here

编辑: Dan Puzey 提出了一个很好的观点,你确定不应该使用

Invoke("useFever",10)InvokeRepeating ("useFever",10,1)

相反?从您的代码看来,您只想在 10 秒内运行 useFever 函数。如果是这样,你应该调用它而不是作为协程运行它,并且 useFever 应该是一个正常的函数。

仅供参考,还有CancelInvoke("useFever")

【讨论】:

  • 如果该代码按照 OP 的意图工作,那么在协程中运行它没有任何价值 - 无论如何它都会在单个帧中运行完成。此外,协程的最后一行很少有 yield 的价值(除非您正在链接协程)。
  • 我同意你的观点,但他把它放在那里,所以当我重构他的代码时,我认为他有他的理由。我认为这是出于“时间”的原因。这不是我的决定
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多