- Home /
How can i make this script work in a "loop"?
Hi, i have this code to fade in / out the panel on the canvas, currently i'm using it on two buttons, one to fade in and one to fade out. I want to make it that automatically it fades out, then in, and out, and so on for, lets say 30 seconds, but i can't get it to work. Here is the code i have. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class UIFader : MonoBehaviour {
public CanvasGroup uiElement;
public void FadeIn()
{
StartCoroutine(FadeCanvasGroup(uiElement, uiElement.alpha, 1, .5f));
}
public void FadeOut()
{
StartCoroutine(FadeCanvasGroup(uiElement, uiElement.alpha, 0, .5f));
}
public IEnumerator FadeCanvasGroup(CanvasGroup cg, float start, float end, float lerpTime = 1)
{
float _timeStartedLerping = Time.time;
float timeSinceStarted = Time.time - _timeStartedLerping;
float percentageComplete = timeSinceStarted / lerpTime;
while (true)
{
timeSinceStarted = Time.time - _timeStartedLerping;
percentageComplete = timeSinceStarted / lerpTime;
float currentValue = Mathf.Lerp(start, end, percentageComplete);
cg.alpha = currentValue;
if (percentageComplete >= 1) break;
yield return new WaitForFixedUpdate();
}
}
}
Thank you so much!
Comment
Answer by Hellium · Mar 15, 2018 at 08:24 PM
public IEnumerator FadeCanvasGroup(CanvasGroup cg, float start, float end, float lerpTime = 1, int count = 1)
{
for( int i = 0 ; i < count ; ++i )
{
for( float t = 0 ; t < lerpTime ; t += Time.deltaTime )
{
cg.alpha = Mathf.Lerp(start, end, t / lerpTime );
yield return null;
}
cg.alpha = end ;
// Swap values
start = start + end;
end = start - end;
start = start - end;
}
}
Thanks @Hellium ! although is not working for me. $$anonymous$$aybe (probably) i'm doing something wrong with it.
What does not work? Have you provided a value greater than 1 for the last parameter count
?
It simply does nothing, yeah, i changed the count to 6 but the alpha is not changing at all !