- Home /
Basic screen fader fading too quickly
I have a basic fading coroutine that is used to fade a black GUITexture to Color.clear using Lerp.Color. The coroutine has a FadeSpeed variable to control the speed of the fade. However, for some reason the fade is occurring much more quickly than the FadeSpeed I have entered. That is, Color.clear (0, 0, 0, 0) is reached before t has reached 1.
Any help would be great.
private float t = 0;
void Awake()
{
// Note, Pixel inset used for pixel adjustments for size and position.
guiTexture.pixelInset = new Rect(0f, 0f, Screen.width, Screen.height);
}
void Start()
{
StartCoroutine(FadeToClear());
}
IEnumerator FadeToClear()
{
while (t < 1)
{
t += Time.deltaTime * (1.0f / FadeSpeed);
guiTexture.color = Color.Lerp(guiTexture.color, Color.clear, t);
yield return new WaitForEndOfFrame();
}
}
Answer by robertbu · Apr 16, 2014 at 06:40 PM
The problem is that you are updating the start position of your Lerp() each frame. You want to hold the start position constant when you use Lerp() this way (with a 't' value that goes from 0.0 to 1.0). Try this:
IEnumerator FadeToClear()
{
Color startColor = guiTexture.color;
while (t < 1)
{
t += Time.deltaTime * (1.0f / FadeSpeed);
guiTexture.color = Color.Lerp(startColor, Color.clear, t);
yield return null;
}
}
Also you can use 'yield return null' to execute once each frame;
Thanks, that did the trick!
If this is the case then I think there may be a similar problem with the S$$anonymous$$lth Game tutorial - ScreenFader script chapter (link text). This doesn't use a t value going from 0-1 but does the Lerp inside Update ins$$anonymous$$d. Changing the fadeSpeed here doesn't change the speed of the fade either.
Note that if 'FadeSpeed' is public, only changes in the Inspector matter. Changing the initialization in code will not change the value once the script has been attached to a game object.
As for 'S$$anonymous$$lth Game Tutorial', their use of Lerp() is very different. The last parameter does not vary from 0.0 to 1.0. Ins$$anonymous$$d the last value remains at approximately the same small fraction frame to frame. The result is that the Lerp() moves towards it destination the same fraction each frame, but since the starting value is also moved, the same fraction represents less 'distance'. The result is an eased movement using Lerp(). This use of Lerp() is non-traditional, but is very common in Unity scripts. It is a very simple way to, without a timer or an easing function, get an eased movement towards some goal.