I have some UI which uses an image that I want to turn slowly invisible after being ignored for a while. I tried creating an Enumerator but I can’t get it to work right.
private IEnumerator fadeOut()
{
int i = 0;
bool finished = false;
while (finished == false)
{
for (i = 0; i < 5; i++)
{
yield return new WaitForSeconds(1f);
}
img.color = new Color(img.color.r, img.color.g, img.color.b, img.color.a - 1);
finished = img.color.a < 1 ? false : true;
yield return new WaitForSeconds(0.2f);
}
}
After a revision, I’ve edited my code but have the same problem-- the transition isn’t smooth, in one frame my alpha levels go from 255 to -1 (rounded up to 0). I’m using an event trigger which uses my functions base on if the mouse goes over my object or leaves it’s box.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class boxController : MonoBehaviour {
Animator anim;
Image img;
Coroutine fade;
Coroutine show;
void Start () {
anim = GetComponent<Animator>();
img = GetComponent<Image>();
fade = StartCoroutine(Wait());
}
public void EnterMouse()
{
anim.SetBool("isUp", true);
if(fade != null)
{
StopCoroutine(fade);
fade = null;
}
show = StartCoroutine(FadeIn());
}
public void ExitMouse()
{
anim.SetBool("isUp", false);
if(show != null)
{
StopCoroutine(show);
show = null;
}
fade = StartCoroutine(Wait());
}
private IEnumerator Wait()
{
for (int i = 0; i < 5; i++)
{
yield return new WaitForSeconds(1f);
}
fade = StartCoroutine(FadeOut());
}
private IEnumerator FadeOut()
{
for (int i = (int)img.color.a - 1; i < 1; i--)
{
img.color = new Color(255, 255, 255, i);
yield return new WaitForSeconds(0.01f);
}
}
private IEnumerator FadeIn()
{
for(int i = (int)img.color.a + 1; i > 254; i++)
{
img.color = new Color(255, 255, 255, i);
yield return new WaitForSeconds(0.005f);
}
}
}