How do I fade a light point?

Hi,

I got a lightpoint with the following script attached to it. When I press the Z key, the light will turn on/off. But how do I get it to fade on/off as well? I can’t seem to get this to work.

Script, which is attached to the light.

private var lanternOn = false;
var fadeFrom = 0.0; 
var fadeTo = 4.0; 
var fadeRate = 10; 
light.intensity = 0;

function Update(){
	if(Input.GetKeyDown("z")){
		if(lanternOn){
			//light.intensity = 0;
			fadeFrom = 4.0; 
			fadeTo = 0.0; 
			light.intensity = Mathf.Lerp(fadeFrom,fadeTo,fadeRate); 
			lanternOn = false;
			
		}else{
			//light.intensity = 4;
			fadeFrom = 0.0; 
			fadeTo = 4.0; 
			light.intensity = Mathf.Lerp(fadeFrom,fadeTo,fadeRate); 
			lanternOn = true;
		}
	}
}

here i made this script and it works. hope it helps

function Update(){
       if(Input.GetButtonDown("f")){
      	 gameObject.light.intensity += 1;
       }
       if(Input.GetButtonDown("c")){
      	 gameObject.light.intensity -= 1;
       }
          
 }

There is a nice example of how to use coroutines for this (and many other tasks) here on the Unity wiki

Here is a function that will fade a light over time. Use values from 0.0 to 1.0 to fade the light up and 0.0 to 1.0 to fade it down.

function FadeLight(l: Light, fadeStart: float, fadeEnd: float, fadeTime: float) {
	var t = 0.0;
	
	while (t < fadeTime) {
		t += Time.deltaTime;
		
		l.intensity = Mathf.Lerp(fadeStart, fadeEnd, t / fadeTime);
		yield;
	}
}