我的代码要点如下:
// 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 方法中的最佳方法是什么?