- Home /
Problem with fading a colour over time
Hi, I'm having some problems with the following code, the '/ fadetime * Time.detlaTime'' part to be specific. I wrote it after looking at the light.color documentation and the example that shows how to fade a colour over a set time.
selection = lightcolour [Random.Range(0, lightcolour.length)];
light.color = selection / fadetime * Time.deltaTime;
It works perfectly fine if I want to change the colour instantly but I can't fade it over a set time. I need to keep the 'light.color = selection' part because other scripts rely on the selection variable.
I get this error, I understand what it means but I just can't think of any other ways of doing this,
'Operator '/' cannot be used with a left hand side of type 'Object' and a right hand side of type 'int'.'
I can't get either of them to work, it's just all co$$anonymous$$g back to problems with not being able to use floating points or integers.
I get 'Cannot convert 'float' to 'UnityEngine.Color'.' Is it possible that this is just something that I can't do with Unity really?
Answer by aldonaletto · Oct 01, 2012 at 02:21 AM
It would be better to use Color.Lerp(color1, color2, t): this returns a color interpolated between the two colors passed, according to t (0=color1, 1=color2).
The code below sets immediately a random color when SetColor is called, and this color fades to the endColor over time during fadeTime seconds:
var endColor = Color.black;
var fadeTime: float = 2.5;
var selection: Color;
var lightcolour: Color[];
private var tColor: float;
function SetColor(){
selection = lightcolour [Random.Range(0, lightcolour.length)];
tColor = 0; // reset timer
}
function Update(){
if (tColor <= 1){ // if end color not reached yet...
tColor += Time.deltaTime / fadetime; // advance timer at the right speed
light.color = Color.Lerp(selection, endColor, tColor);
}
}
PS: The error you've encountered at first was probably caused by selection being untyped: when the compiler can't deduce the variable type, it assumes the object type, which can hold any standard type.