# Spot Light color fade in Unity 3d

I have a scene where many spot lights are focused on the screen. All have red color and same intensity. What I want is that the red Color(0,0,0,1) value should increase and decrease in a fading effect over a period of time. I thought of using Color.Lerp() but can not achieve it. What currently I am doing is attaching this script to all the instances of the SpotLight.

void Update()
{
if(Time.time()%120==0)
transform.light.color=new Color(Random.Range(0,255),0,0,1);
}


I know I am missing something big here. Help is appreciated. Thanks in advance.

The problem is on the line if(Time.time()%120==0)

By doing that, you divide the timestamp by 120 and then compare if the decimals are zero. That will happen really rarely as the timestamp will have quite a lot of different values. What you should do instead is to calculate the colour every frame. Perhaps something like this will do:

void Update()
{
transform.light.color=new Color((Mathf.Sin(Time.time()) + 1) / 2,0,0,1);
}


This will smoothly increase and decrease the light over time. The "magic" is in the Mathf.Sin() method.

• Exactly what I was looking for. And Thanks a ton for headsup on the timestamp divition. :) – Abhishek Deb Nov 19 '13 at 8:44
• Can we somehow increase the speed at which its oscillating the values? – Abhishek Deb Nov 19 '13 at 8:46
• You could change the speed by modifying the value that is given to Mathf.Sin(). The timestamp will grow linearly when time goes on, thus creating a linear sin curve. By making this value change more rapidly or more settle you can modify the rate the color flickers. Perhaps try multiplying the timestamp by 1.05f or try making it to power of two or something like that. – Lasse Nov 19 '13 at 8:56
• Glad to be of service :) – Lasse Nov 19 '13 at 9:01