5

我的代码要点如下:

// Play the first beat
audio.PlayOneShot(beat);

// Show 1st heartbeat border flash
TweenAlpha.Begin(heartbeatPanel.gameObject, 0.1f, currentStress);
yield return new WaitForSeconds(0.1f);
TweenAlpha.Begin(heartbeatPanel.gameObject, 0.5f, 0);

yield return new WaitForSeconds(interval);

// Play the second beat
audio.PlayOneShot(beat);

// Show 2nd heartbeat border flash
TweenAlpha.Begin(heartbeatPanel.gameObject, 0.1f, currentStress);
yield return new WaitForSeconds(0.1f);
TweenAlpha.Begin(heartbeatPanel.gameObject, 0.5f, 0);

yield return new WaitForSeconds(interval * 2);

现在我想将上面的代码拆分成一个带有 2 个调用的 IEnumerator 方法。

这就是我想出的:

StartCoroutine(PlayBeat(currentStress, interval));
StartCoroutine(PlayBeat(currentStress, interval * 2));

// ...

IEnumerator PlayBeat(float currentStress, float interval)
{
     audio.PlayOneShot(beat);

     TweenAlpha.Begin(heartbeatPanel.gameObject, 0.1f, currentStress);
     yield return new WaitForSeconds(0.1f);
     TweenAlpha.Begin(heartbeatPanel.gameObject, 0.5f, 0);

     yield return new WaitForSeconds(interval);
}

这样做的问题是,不是节拍以正确的间隔发声,而是两个节拍同时响起,因为我在无限循环中进行了这些调用,Unity 崩溃了,因为没有考虑间隔。

将上面的两个重复代码块提取到单个 IEnumerator 方法中的最佳方法是什么?

4

1 回答 1

6

Unity3d 的协程可以嵌套。要等待嵌套协程,您需要让出它。所以你的功能PlayBeat很好;您只需要以 unity3d 理解为“等到完成”的方式启动它。您的示例将如下所示:

yield return StartCoroutine(PlayBeat(currentStress, interval));
yield return StartCoroutine(PlayBeat(currentStress, interval * 2));

It's uncanny how similar that looks to C# 5's async/await. At some level this is unsurprising since they're both compiler-transformed "coroutine" statemachines - but it's still neat to see the similarity.

于 2013-03-12T09:06:58.237 回答