- Home /
Gradually change light intensity
I've been trying to constantly change the intensity of my light to a random amount, but I want it done slowly as if it were pulsating. So far I've tried:
Using Mathf.MoveTowards in the Update method
if (light.intensity == targetIntensity)
{
targetIntensity = getNewIntensity();
currentIntensity = light.intensity;
}
light.intensity = Mathf.MoveTowards(currentIntensity, targetIntensity, pulseSpeed + Time.deltaTime * 3);
But this results in the light quickly flickering or getting stuck somewhere instead of a slow progress.
Using Mathf.PingPong
light.intensity = Mathf.PingPong(pulseSpeed * Time.deltaTime, maxIntensity - minIntensity);
But this always starts with intensity at 0 and barely increases over time.
The most success I've gotten so far is using a Coroutine (which was the first thing I tried) but it also seems to change really slow and for some reason going backwards sometimes (that is, the current is 0.6, target is 0.75 it starts going up to 0.68 and then goes back down and lingers around 0.65). It also jumps in intensity a couple times before normalizing.
private IEnumerator FlickerLight()
{
while (true)
{
if (light.intensity == targetIntensity)
{
targetIntensity = getNewIntensity();
currentIntensity = light.intensity;
}
light.intensity = Mathf.MoveTowards(currentIntensity, targetIntensity, Time.deltaTime * 10);
print("Target: " + targetIntensity + " current: " + currentIntensity);
yield return new WaitForSeconds(pulseSpeed);
}
}
Variables are as follow:
minIntensity = 0.6f;
maxIntensity = 1f;
flickerSpeed = 3f;
pulseSpeed = 1f;
For context, what I want to do is simulate the effect of lava on the ground, I've also tried changing the angle of the light source with similar results.
Your answer
![](https://koobas.hobune.stream/wayback/20220612143355im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Creating an object at another object's location 1 Answer
Light creates distortion on mesh? 1 Answer
No shadows. 2 Answers
Changing radius/diameter of spotlight 2 Answers
Horrible glitch/black spots with Lightmapping in Unity 5 5 Answers