I’ve checked the existing questions as well as implementing an example from the Unity manual, but for some reason I am getting an identical issue no matter which solution I implement. An icon’s alpha lerps gradually from 1 to 0 the first time the coroutine is called, but subsequent calls go directly from one extreme to the other without lerping. (More info below code)
Here is the currently implemented code for the coroutine:
[SerializeField]
Image lightHUD;
[SerializeField]
Image darkHUD;
void Start ()
{
EventManager.Instance.OnVisible += OnLighten;
EventManager.Instance.OnInvisible += OnDarken;
}
void OnDestroy()
{
EventManager.Instance.OnVisible -= OnLighten;
EventManager.Instance.OnInvisible -= OnDarken;
}
void OnLighten()
{
StartCoroutine(FadeToLight());
}
void OnDarken()
{
StartCoroutine(FadeToDark());
}
IEnumerator FadeToDark()
{
Color cl = lightHUD.color;
Color cd = darkHUD.color;
for (float f = 1f; f >= 0; f -= 1/100f)
{
cl.a = f;
lightHUD.color = cl;
cd.a = 1 - f;
darkHUD.color = cd;
yield return null;
}
}
IEnumerator FadeToLight()
{
Color cl = lightHUD.color;
Color cd = darkHUD.color;
for (float f = 1f; f >= 0; f -= 1/100f)
{
cl.a = 1 - f;
lightHUD.color = cl;
cd.a = f;
darkHUD.color = cd;
yield return null;
}
}
I currently have an event system coded in one of my scripts’ Update() functions. This calls the functions in the HUD script above. Basically, if the character is near a light and visible, a brightly colored HUD icon’s alpha moves up to indicate that he is visible. When the player is in the dark, this icon’s alpha moves down and a similar but darker icon’s alpha moves up to indicate he is in the dark.
So far, so good. This part works properly, but only once. Anytime afterward, when walking toward or away from a light, the alpha for both icons jumps straight to their respective extremes after the allotted lerp time, but without lerping (e.g. lerp is time is 1 sec, character walks into light, nothing changes for 1 sec, then bright icon’s alpha jumps right to 1 from 0 and dark jumps right to 0 from 1)
Any ideas? Thanks in advance!