It’s possible to fade a sprite in Unity over time by modifying the alpha channel of its colour.
There are two ways to do this, either with Lerp, which involves blending between two colours using a weighted value, or with Move Towards.
Move Towards is a mathematical function in Unity that can be used to move a float value towards a target at a set speed, without going over.
It can be used to modify the alpha channel of a colour over a period of time.
Like this:
using UnityEngine;
using System.Collections;
public class FadeSprite : MonoBehaviour
{
public float targetValue;
SpriteRenderer spriteToFade;
void Start()
{
spriteToFade = gameObject.GetComponent<SpriteRenderer>();
StartCoroutine(FadeSpriteAlpha(targetValue, 1));
}
IEnumerator FadeSpriteAlpha(float targetOpacity, float duration)
{
Color startValue = spriteToFade.color;
float speed = 1 / duration;
while (spriteToFade.color.a != targetOpacity)
{
spriteToFade.color = new Color(
startValue.r,
startValue.g,
startValue.b,
Mathf.MoveTowards(spriteToFade.color.a, targetOpacity, speed * Time.deltaTime));
yield return null;
}
}
}
Normally, Move Towards allows a value change to be controlled using speed however, in this method, the required speed is calculated from a duration instead.
Like Lerp, this allows you to control the fade based on how long you want it to take, as opposed to the speed at which the sprite should change its opacity.
However, unlike Lerp which, under typical circumstances, will always take the same amount of time, the Move Towards method can be useful if the sprite is likely to partially fade in or out, such as if the fading process was interrupted before it finished.
This allows the fade to take place at the correct rate, even though the required fade duration is now shorter.