When I change the background image sprite, it breaks my code for fade in and fade out:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Fade_Background : MonoBehaviour
{
public Image BackgroundImage;
public int _Delay;
private bool _FadeOut = false;
private bool _Running = false;
private bool _rotate = false;
private int _Image = 0;
private void Start()
{
Change_Image();
GameObject imageObject = GameObject.FindGameObjectWithTag("imgBackground");
BackgroundImage = imageObject.GetComponent<Image>();
}
void Update()
{
if (!_Running)
{
if (_FadeOut)
{
StartCoroutine(FadeOut());
if(_rotate) { Change_Image(); }
}
else
{
StartCoroutine(FadeIn());
}
}
}
private void Change_Image()
{
_rotate = false;
switch (_Image)
{
case 0:
BackgroundImage.sprite = Image_Game_Data._Templo_Mayor;
break;
case 1:
BackgroundImage.sprite = Image_Game_Data._Pyramid_Of_The_Sun;
break;
case 2:
BackgroundImage.sprite = Image_Game_Data._El_Castillo;
break;
case 3:
BackgroundImage.sprite = Image_Game_Data._Dzibilchaltun;
break;
case 4:
BackgroundImage.sprite = Image_Game_Data._Kinich_Kakmo;
break;
case 5:
BackgroundImage.sprite = Image_Game_Data._Cenote_Xlacah;
break;
case 6:
BackgroundImage.sprite = Image_Game_Data._Ball_Court;
break;
}
if (_Image == 6) { _Image = 1; } else { _Image++; }
}
IEnumerator FadeOut()
{
_Running = true;
if (BackgroundImage == null)
{
GameObject imageObject = GameObject.FindGameObjectWithTag("imgBackground");
BackgroundImage = imageObject.GetComponent<Image>();
}
Color tmpColor = BackgroundImage.color;
while (BackgroundImage.color.a > 0.0f)
{
tmpColor.a -= Time.deltaTime / 4;
BackgroundImage.color = tmpColor;
yield return null;
}
//if (BackgroundImage.color.a < 0.0f) { _rotate = true; }
_FadeOut = false;
_Running = false;
yield return null;
}
IEnumerator FadeIn()
{
_Running = true;
if (BackgroundImage == null)
{
GameObject imageObject = GameObject.FindGameObjectWithTag("imgBackground");
BackgroundImage = imageObject.GetComponent<Image>();
}
Color tmpColor = BackgroundImage.color;
while (BackgroundImage.color.a < 1.0f)
{
tmpColor.a += Time.deltaTime / 4;
BackgroundImage.color = tmpColor;
yield return null;
}
yield return new WaitForSecondsRealtime(_Delay);
_FadeOut = true;
_Running = false;
yield return null;
}
}