Light Fading Script not working

I have a script which doesn’t work. What I want the script to do is to fade a directional light from a high intensity to off.

using UnityEngine;
using System.Collections;

public class LightFade : MonoBehaviour {
	public float fadeSpeed = 2f;
	public float highIntensity = 0.4f;
	public float lowIntensity = 0f;
	public float changeMargin = 0.2f;
	
	private float targetIntensity;
	
	void Awake() {
		light.intensity = 0.4f;
		targetIntensity = lowIntensity;
	}
	
	void Update() {
		if(Input.GetKeyUp("z")) {
			light.intensity = Mathf.Lerp(light.intensity, targetIntensity, fadeSpeed * Time.deltaTime);
		}
	}
}

Hello, the reason is that it’s only changing while your key is “Up” try this instead.

using UnityEngine;
using System.Collections;

public class LightFade : MonoBehaviour
{
    public float fadeSpeed = 2f;
    public float highIntensity = 0.4f;
    public float lowIntensity = 0f;
    public float changeMargin = 0.2f;

    private float targetIntensity;
    private bool amIFading;

    void Awake()
    {
        light.intensity = 0.4f;
        targetIntensity = lowIntensity;
        amIFading = false;
    }

    void Update()
    {
        if (Input.GetKeyUp("z"))
        {
            amIFading =! amIFading;
        }

        if (amIFading == true)
        {
            light.intensity = Mathf.Lerp(light.intensity, targetIntensity, fadeSpeed * Time.deltaTime);
        }
    }

}

Using this you can turn fading on and off using the “Z” key.

Best Regards
Jona