1
\$\begingroup\$

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.

\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Exactly what I was looking for. And Thanks a ton for headsup on the timestamp divition. :) \$\endgroup\$ Nov 19, 2013 at 8:44
  • \$\begingroup\$ Can we somehow increase the speed at which its oscillating the values? \$\endgroup\$ Nov 19, 2013 at 8:46
  • \$\begingroup\$ 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. \$\endgroup\$
    – Lasse
    Nov 19, 2013 at 8:56
  • \$\begingroup\$ Glad to be of service :) \$\endgroup\$
    – Lasse
    Nov 19, 2013 at 9:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .