The essence of my code is this:
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);
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 * 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?
source
share