- Home /
Multiple coroutine exicution order
Hello
I have written a coroutine for fad in and fade out the sound effect
private IEnumerator FadeInOut(AudioSource source, float toVal, bool shouldStop, float lerpDuration = 5) { %|-237000201_2|% %|32912738_3|% %|-1584710926_4|% %|2065127481_5|% %|83609385_6|% // lerp logic for executing in a given time. %|1478197646_7|% %|-880432233_8|% %|-1229117739_9|% %|277229335_10|% %|1474934169_11|% %|1679487772_12|% %|1387183729_13|% %|-75361698_14|% %|2100960351_15|% %|-1328175113_16|% %|-1906317594_17|% %|-1665580146_18|% To Fade In and Out the sound i have this methods
private void FadeInMusic(AudioSource sourceToFadeIn)
{
// this will fade in the volume source.volume to 1 (Normally 0 to 1) StartCoroutine (FadeInOut (sourceToFadeIn,1,false,m_fadeDuration)); }
private void FadeOutMusic(AudioSource sourceToFadeOut) { // this will fade in the volume source.volume to 0 (Normally 1 to 0) StartCoroutine (FadeInOut (sourceToFadeOut,0,true,m_fadeDuration)); }
`
if i call FadeInMusic() and FadeOutMusic() back to back (or with a very small delay) by passing the same Audio source, two instances of FadeInOut coroutine starts to execute
since FadeInMusic() is called first it will finish execution before FadeOutMusic() Problem i am facing here is in unity is Volume is taking the value from FadeInMusic() function call coroutine, once it is done executing then it will take the value from FadeOutMusic() function call coroutine.
What i have to do to change the coroutine execution order or overriding volume value from 2nd coroutin ? ? As i want the value from FadeOutMusic() function call coroutine.
Answer by rockin · Aug 31, 2016 at 11:36 AM
You can create a private variable to hold your state:
private int step = 0;
IEnumerator Coroutine1(){
if (step == 0) {
// Do stuff.
step++;
}
}
IEnumerator Coroutine2(){
if (step == 1) {
// Do stuff.
step++;
}
}
....
IEnumerator CoroutineLast(){
if (step == 1) {
// Do stuff.
step = 0;
}
}
Hello rockin, thanks for the reply.
Could you please explain in detail.
As i need the unity to update the value from last coroutine called, but unity is considering the value of first coroutine called.
from your above example lets take coroutine1 and coroutine2, called on the same audio source. since the coroutine2 is called last i need unity to consider only this value and apply to audio source, but unity still stick on coroutine1 and update audio source by coroutine1 value, once coroutine1 finish executing then it will start taking leftover value from coroutine2.