- Home /
How can I fade in/out an object nonstop automatic ?
The fade method :
IEnumerator FadeTo(Material material, float targetOpacity, float duration)
{
Color color = material.color;
float startOpacity = color.a;
float t = 0;
while (t < duration)
{
t += Time.deltaTime;
float blend = Mathf.Clamp01(t / duration);
color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);
material.color = color;
yield return null;
}
StartCoroutine(FadeTo(objectToFade.GetComponent<Renderer>().material, 1, 3));
}
Then I'm calling it from the Start :
public void Start()
{
StartCoroutine(FadeTo(objectToFade.GetComponent<Renderer>().material, 0, 3));
}
So now it's fading out in 3 seconds then fading in back in 3 seconds then stop.
But I want it to keep fading out/in/out/in....nonstop automatic. each 3 seconds fade out then each 3 seconds fade in and so on nonstop automatic.
And for example the duration is 0 then fade out/in very quick if the duration 23 then fade out in 23 seconds then fade in in 23 seconds.
The problem is how to make it nonstop ?
Answer by swanne · Jan 09 at 12:55 PM
Hey, Try using InkokeRepeating instead of coroutines. Check out the docs here - https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html
Answer by GMLibra · Jan 09 at 04:08 PM
I don't believe your repetition is actually stopping .. you just see it fading out once to opacity 0 because that's hardcoded in Start, then FadeTo repeatedly pushes opacity to 1 because you're hardcoded for 1 inside FadeTo.
instead of StartCoroutine(FadeTo(objectToFade.GetComponent().material, 1, 3));
try starting the coroutine inside the FadeTo method using startOpacity to send the opacity back to whatever it started as.
StartCoroutine(FadeTo(objectToFade.GetComponent().material, startOpacity , 3));
If it went from 0 to 1, it will go back to 0. If it went from 1 to 0, it will go back to 1, and so on.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Fading out doesn't fade out, but instantly goes from black to clear 0 Answers
Fade In / Out not working C# 1 Answer
Fading from my splash screen 1 Answer