Search code examples
c#unity-game-enginecolorslerp

Lerp the alpha value of a color


I want to change the alpha value (transparency) of a color back and forth:

private void Awake()
{
    material =  gameObject.GetComponent<Renderer>().material;   
    oColor   = material.color; // the alpha here is 0
    nColor   = material.color;
    nColor.a = 255f;
}
private void Update()
{
    material.color = Color.Lerp(oColor, nColor, Mathf.PingPong(Time.time, 1));
}

This doesn't work, the color instantly changes to white, and it keeps blinking the original color. I'm following this.


Solution

  • In fact the alpha color of the Material goes from 0 to 255, however these values in C# are translated from 0 to 1, making 1 equal to 255. This is a script I made a while ago, maybe you can use it:

    public class Blink : MonoBehaviour 
    {
        public Material m;
        private Color c;
        private float a = .5f;
        private bool goingUp;
    
        private void Start()
        {
            c = m.color;
            goingUp = true;
        }
        private void Update()
        {
            c.a = goingUp ? .03f + c.a : c.a - .03f;
    
            if (c.a >= 1f) 
                goingUp = false;
            else if (c.a <= 00)
                goingUp = true;
    
            m.color = c;
        }
    }