I am trying to make my game fade in and fade out with Coroutine. Fading in ran as it should do but for fading out, it runs as it should in play mode but after I build and run my game, it look like the Update function keep calling StartCoroutine () again and again. I don’t know why it runs smoothly in play mode but doesn’t in build and run. My code is shown below. (The update function and fadeOut is from a separate scripts)
public float LoadOutTime = 1.2f;
public FadingInOut FadingInOut;
private bool Out;
void Awake (){
Out = false;
}
void Update () {
if (Out == false && Time.time > LoadOutTime) {
FadingInOut.StartCoroutine("FadeOut");
Out = true;
}
}
And FadeOut Coroutine is from another script.
public class FadingInOut : MonoBehaviour {
public float fadeSpeed = 1.1f;
public Color fadeColor;
public string nextLevel;
public bool fadingOut = false;
private RectTransform rect;
private float time;
private Image imageContainer;
void Awake(){
time = Time.time;
imageContainer = GetComponentInChildren<Image> ();
rect = imageContainer.GetComponent<RectTransform> ();
imageContainer.color = fadeColor;
rect.localScale = new Vector3 (1, 1, 1);
}
public IEnumerator FadeOut(){
time = 0.0f;
rect.localScale = new Vector3 (1, 1, 1);
while (imageContainer.color != fadeColor) {
time += Time.deltaTime;
imageContainer.color = Color.Lerp (Color.clear,fadeColor, fadeSpeed*time);
yield return new WaitForSeconds(0.02f);
}
Application.LoadLevel (nextLevel);
}
}
Thanks in advance.