3

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.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Abdou023
  • 1,654
  • 2
  • 24
  • 45

2 Answers2

1

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;
    }
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Hristo
  • 1,805
  • 12
  • 21
  • 1
    I notice I have hardcoded the speed which is `.03f`, if necessary you can make it a variable and adjust it accordingly. – Hristo May 12 '17 at 19:40
  • Of course, this particular script will cause the creation of a new instanced material every frame. May be advisable to use a [Material Property Block](https://docs.unity3d.com/ScriptReference/MaterialPropertyBlock.html) instead. – Draco18s no longer trusts SE May 12 '17 at 20:23
  • What? but I never say new in the Update – Hristo May 12 '17 at 20:29
  • 1
    No, you don't, but that's what happens when you modify a material's properties: Unity automatically clones it for you. – Draco18s no longer trusts SE May 12 '17 at 20:31
  • There are ways around it, but for "instanced" materials without creating new instances (e.g. 12 objects with the same *base material*, but different colors), MPB is the way to go. Just wanted to throw that note out there because modifying the material directly *does work* but might have performance impacts for some future reader. – Draco18s no longer trusts SE May 12 '17 at 20:50
0

You can try this:

void FixedUpdate ()
{
    material.color = new Color (0f, 0.5f, 1f, Mathf.PingPong(Time.time, 1));
}

Here the color is blue, (RGB 0, 128, 255) the "Mathf.PingPong(Time.time, 1) handles the alpha.

The effect is fully visible when you set the material "rendering mode" to "transparent" in the inspector :)

Note:

  • using the "transparent" rendering mode will make the object transparent when the alpha layer goes down to 0,

  • using the "fade" rendering mode will make the object become completely invisible when the alpha layer goes down to 0.