Problems with refactoring IEnumerator method with multiple outputs

The essence of my code is this:

// 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);

Now I want to break the above code into one IEnumerator method with two calls.

Here is what I came up with:

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);
}

The problem is that instead of the bits sounding at their correct interval, both bits sounded at the same time, and since I had these calls in an infinite loop, Unity crashed because the intervals were not considered.

What is the best way to extract the two repeating blocks of code above into a single IEnumerator method?

+5
source share
1 answer

Unity3d Coroutines . , . , PlayBeat ; , unit3d , " ". :

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

, # 5 async/await. - , "coroutine" statemachines, , .

+6

All Articles