- Home /
UI Image CrossFadeAlpha IEnumerator
I want to make a image fade in then fade out when fuel reaches a certain amount.
In my update function i have
if (Fuel.value <= 20) {
StartCoroutine (LowFuelFadeInOut ());
}
Then the IEnumerator is
IEnumerator LowFuelFadeInOut ()
{
LowFuel.gameObject.SetActive (true);
//FADE IN
LowFuel.CrossFadeAlpha (1f, 1.5f, false);
yield return new WaitForSeconds (2f);
//FADE OUT
LowFuel.CrossFadeAlpha (0f, 1.5f, false);
yield return new WaitForSeconds (2f);
//FADE IN AGAIN
LowFuel.CrossFadeAlpha (1f, 1.5f, false);
yield return new WaitForSeconds (2f);
//FADE OUT AGAIN
LowFuel.CrossFadeAlpha (0f, 1.5f, false);
LowFuel.gameObject.SetActive (false);
}
The problem is that the IEnumerator is called again over and over every frame, so after the first fade in it tries to do the fade out and also the fade in again. So what happens to the image is that the image stays at the same alpha and slightly flickers.
Note: I need to be checking the fuel constantly or at least check the value each time it changes so taking the coroutine out of update (or similar) is not an option.
Does anyone have any ideas on what I could do so that the coroutine is only called once?
Answer by JackTenSeven · Aug 04, 2017 at 03:54 AM
Had a idea. May be possible to make the update check for a certain value that the fuel going down will hit. But my Fuel right now is a float so it is hard to find a certain value. I could change the fuel from float to a int and just increase the int number of total fuel so it goes down in the same speed.
Answer by thepopil · Aug 04, 2017 at 04:05 AM
If you want to make sure the StartCoroutine doesn't get called repeatedly, you can set a flag while it's being run. Declare "bool isFuelAnimating = false;" or something in your class and do something like this:
if(!isFuelAnimating)
StartCoroutine (LowFuelFadeInOut ());
and then
IEnumerator LowFuelFadeInOut ()
{
isFuelAnimating = true;
// Do stuff
isFuelAnimating = false;
}