- Home /
Color.Lerp is not working
I have a cube that I want to shift slowly from white to red, then from red to white. Right now, it just flickers very fast between the two without and sign of a Lerp. I'll post the code. !whiteToRed means that it is going from red to white. Also, there are no Errors in the Console. Thanks!
#pragma strict
var red : Color = new Color(1, 0, 0);
var white : Color = new Color(1, 1, 1);
public var speed : float = 100;
var whiteToRed : boolean = true;
function Start () {
}
function Update () {
if(whiteToRed){
renderer.material.color = Color.Lerp(white, red, Time.deltaTime * speed);
}
if(!whiteToRed){
renderer.material.color = Color.Lerp(red, white, Time.deltaTime * speed);
}
whiteToRed = !whiteToRed;
}
Answer by robertbu · Feb 01, 2014 at 06:26 AM
To start with let me give you an alternate bit of code that will cycle between white and red. It uses Mathf.PingPong() to cycle the colors:
var red : Color = new Color(1, 0, 0);
var white : Color = new Color(1, 1, 1);
public var speed : float = 0.5;
function Update () {
renderer.material.color = Color.Lerp(white, red, Mathf.PingPong(Time.time * speed, 1.0));
}
As for your code, there are a couple of different ways to use Lerp. When the end points are fixed as you have here, you need to vary the last parameter between 0.0 and 1.0...that is you would need to create some sort of timer. There a use of Lerp that produces an eased movement towards the goal. Your speed would have to be much lower, and you would use it like:
renderer.material.color = Color.Lerp(renderer.material.color, red, Time.deltaTime * speed);
Also your code flipping 'whiteToRed' every frame. You would only flip it when the color is at or near the destination color.
I decided to use your code, ins$$anonymous$$d of $$anonymous$$e. It works a lot better and uses less memory. Thanks!
Is there a way to make it stay white for a little longer?
With this method ($$anonymous$$athf.PingPong()) the time it is red and the time it is white will be the same. You can adjust 'speed' to slow things down. To make different times for each color, you will need approach the problem differently...more like your original code.
Answer by Cassos · May 02, 2020 at 11:56 PM
Already solved but I found the problem if anybody cares:
Color.Lerp works like this:
Color.Lerp(current, target, delta * speed)
But you didnt assign the current as the color of the renderer but just "red". That causes the color to always be the same.