I am using color.lerp on a sprite renderer to interpolate between yellow and red based on values I have in a dataset. I also want the transparency of the sprites to depend on the value so lower values will be more transparent. The color.lerp works fine but I am now having trouble getting the alpha levels of the sprite to depend on the value as well! Here is my code so far:
using UnityEngine;
using System.Collections;
public class Intensity : MonoBehaviour {
public float value;
private float alpha;
void Start() {
if (GetComponent<SpriteRenderer> ()) {
SpriteRenderer r = GetComponent<SpriteRenderer> ();
r.color = new Color32 ();
r.color = Color.Lerp (Color.yellow, Color.red, value / 100);
}
if (GetComponent<MeshRenderer> ()) {
MeshRenderer r = GetComponent<MeshRenderer> ();
Material m = r.material;
Color c = new Color ();
m.color = c;
alpha = Mathf.Lerp(0, 1, value/100) ;
c.a = alpha;
}
}
}
Any ideas to make this work would be greatly appreciated!
Thank you, Jen
In this code:
Material m = r.material;
Color c = new Color ();
m.color = c;
alpha = Mathf.Lerp(0, 1, value/100) ;
c.a = alpha;
Because Color
is a struct, any get
and set
properties such as Material.color
will pass by value. This means that c
and m.color
are separate values that don't affect each other.
You can avoid that by assigning to m.color
last:
Color c = Color.Lerp(newYellow, Color.red, value / 100);
c.a = Mathf.Lerp(0, 1, value/100);
m.color = c;
If that doesn't make sense, see if you can understand why this won't work:
m.color.a = 0;
You instead have to get the value, make a change, and assign the new value:
Color c = m.color;
c.a = 0;
m.color = c;