- Home /
Lerp Color doesn't work
Hey, I've made this script tho I'm having a little problem with it, doesn't change colors for some reason :/
public Color[] bgColors;
private float t = 0.05f;
private Renderer rend;
// Use this for initialization
void Awake()
{
rend = GetComponent<Renderer>();
}
void Start ()
{
Invoke ("changeColor", 1f);
}
// Update is called once per frame
void Update () {
}
void changeColor()
{
Debug.Log ("IM HERE");
Color.Lerp(rend.material.color, bgColors[Random.Range(0, bgColors.Length)],t);
Invoke ("changeColor", 1f);
}
Answer by DiegoSLTS · May 31, 2015 at 04:23 PM
First, If you don't change the value of "t" you'll always get the same color from Color.Lerp. Check again the documentation of Color.Lerp, the "t" value should go from 0 to 1 to get the proper transition: http://docs.unity3d.com/ScriptReference/Color.Lerp.html
Second, Lerp returns a color, it doesn't change the one you provided, so you have to use the returned color for something. Again, look at the docs.
Third, I don't understand what you're trying to do, but I guess you're also confused about the Invoke method.
If you want to lerp from one color to another and want the transition to last 1 second you have to update the color on every frame. Your "Invoke("changeColor",1f);" line calls the changeColor only once every second.
Also, you're changing the second color to a random color for the list on every call to that function, that would give really weird results.
I'll make a guess here, I think you want this code:
public Color[] bgColors;
private Renderer rend;
// Use this for initialization
void Awake()
{
rend = GetComponent<Renderer>();
}
void Start ()
{
StartCoroutine(changeColor());
}
IEnumerator changeColor()
{
Color startColor = rend.material.color;
Color endColor = bgColors[Random.Range(0, bgColors.Length)];
float t = 0f;
while(t <= 1f) {
rend.material.color = Color.Lerp(startColor,endColor,t);
t += Time.deltaTime;
yield return null;
}
StartCoroutine(changeColor());
}
Answer by maccabbe · May 31, 2015 at 04:25 PM
Color.Lerp(Color a, Color b, float t)
returns a new Color. To change one of the passed colors you have to assign to the passed color, i.e.
rend.material.color=Color.Lerp(rend.material.color, bgColors[Random.Range(0, bgColors.Length)],t);
Your answer
Follow this Question
Related Questions
lerp transparency back and forth, while cycling through rainbow? 0 Answers
How to make OnTriggerStay ColorLerp start all over again OnTrigger? 2 Answers
changes to colour alpha affect RGB values, but not in the same way 1 Answer
Lerp color of verts with position bigger than 1 1 Answer
Trouble with OnGUI and Update 3 Answers