Alternative fader

Here’s an alternative way to do the fading. It uses Mathf.MoveTowards, which moves gradually towards a value and does the computations and worries about direction under the hood, so you don’t have to do so much manually. An advantage is one fade routine that fades to any value, called by fade in and fade out.

I also used Mathf.Approximately to determine when the target alpha is reached. This is a “sleep easier” thing to do, called “defensive programming” in the real world: although the way Mathf.MoveTowards is written we don’t see rounding errors, it feels better to know we are protected from them and on modern systems with fast, pipelined floating point units, Mathf.Approximately takes almost no time at all.

There are other Mathf. (and Vector3. and Quaternion.) methods for moving toward something gradually. They are good timesavers since you don’t have to derive a formula each time. In this case, you only need to derive that delta time is Time.deltatime/fadeTime to put in the last argument of MoveTowards, and as I said, increasing vs. decreasing is handled automatically.

If you wanted to be more fancy, you could also employ a Curve so the fade isn’t actually linear. :slight_smile:

Privacy & Terms