I have a script that fades the screen in and out, but I’d like to make it so that this happens over a precise number of seconds by shifting alpha from 0 to 1 and vice versa as necessary.
Here’s how I call the relevant function from other scripts:
ScreenFading.ScreenFader.FadeOut(4f);
4f is where I’d like to put the time the fade should take in seconds.
Here’s the function on ScreenFading:
public void FadeOut(float fadeTime)
{
StartCoroutine(DoFadeOut(fadeTime));
}
Here’s the co-routine on ScreenFading:
IEnumerator DoFadeOut(float doFadeTime) //i.e. make screen black
{
while (?????)
{
?????
yield return null;
}
yield return null;
}
Here’s the bit on ScreenFading where it draws the black texture over the screen:
I’d like to make blackAlpha shift from 1 to 0 over doFadeTime seconds (4 in my original example). I’m not even sure how to start though - all I know is that I’d probably use Time.deltaTime. Any suggestions?
Well 0/Number = 0, and Number/Number = 1. So if you want to slowly increment from 0 to 1 over Number seconds, you’d probably want to calculate some currentTime/TotalTime, and then increment currentTime by the Time.deltaTime of the frame.
Here’s a special variety of for loop which I use for this sort of situation:
public IEnumerator ChangeSomeValue(float oldValue, float newValue, float duration) {
for (float t = 0f; t < duration; t += Time.deltaTime) {
someValue = Mathf.Lerp(oldValue, newValue, t / duration);
yield return null;
}
someValue = newValue;
}
The “someValue” line is the main one that changes, and you simply assign that to wherever it should be. You can do this with just about any value type that supports lerping.
PS: Don’t use OnGUI (except for like, the most basic of debugging stuff). The new GUI system (based on Canvas) is objectively better.
Personally, I have used tweening engines for many of these things. Does look like you have a couple of good suggestions here as well, but just to toss out other options. LeanTween and Dotween both are available for free and can handle these things very well.
Those are great options if you want something more than a linear transition, for example a curvy colour transition for health bars as they shrink (50-100% is green, 10-49% is yellow, lower red) - or to fade the screen faster towards the darkest portion of a fadeout.
You can also use animations for this (which is much easier on the Canvas system than the OnGUI system, as you can literally just animate the color you want to change, no code needed at all except to trigger the animation in the first place.)