- Home /
 
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;
         }
     }
 }
 
              Answer by Mander · Aug 30, 2012 at 02:28 PM
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;
        }
           
  }
 
              Thank you for your input, but I think you misunderstood my post. With your script I can adjust the intensity. However, I am asking for a way to FADE lightning. See it as a lantern you can hold. When you hold the lantern, I don't want the light to just pop up, but I want it to fade it.
Answer by andeeeee · Aug 30, 2012 at 02:30 PM
There is a nice example of how to use coroutines for this (and many other tasks) here on the Unity wiki
Hi andeeeee. On the description it says: "Fade GUITextures or anything that has a material (including GUIText objects) at any time with these simple coroutines that can be called from anywhere." I guess that won't work on a light point?
It was more as an illustration of the technique, actually, but I guess I should have been clearer. I've answered again with the exact code you need.
Answer by andeeeee · Aug 30, 2012 at 02:59 PM
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;
     }
 }
 
              Your answer
 
             Follow this Question
Related Questions
Fade Float Function 2 Answers
Changing a bunch of lights intensity 2 Answers
Setting Scroll View Width GUILayout 1 Answer
Fading a text gui style 3 Answers
Can someone help me fix my Javascript for Flickering Light? 6 Answers