Lights on Script not always working

Hello,
so I created a basic script that when “e” is pressed down the light specified turns on, then off again if you press it again. For some reason though the light doesn’t always turn on when “e” is pressed and I have no idea why. Here’s my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightsOnPress : MonoBehaviour
{
    public AudioSource Click;
    public Light Lights;
    public GameObject Text;
    public bool LightisOn;

    public void Start()
    {
        LightisOn = Lights.enabled = false;
    }



    void OnTriggerStay(Collider other)
    {
        Text.gameObject.SetActive(true);
    
         if (Input.GetKeyDown("e"))
        {
           

            if (LightisOn)
            {
                LightisOn = Lights.enabled = false;
                Click.Play();
            }
            else
            {
                LightisOn = Lights.enabled = true;
                Click.Play();
            }
       }
    }

     void OnTriggerExit(Collider other)
    {
        Text.gameObject.SetActive(false);
    }
}

It’s simple. Input event information should be processed in Update. Processing these events in FixedUpdate can lead to unpredictable results. When it comes to your code, the problem is that you check for the input inside OnTriggerStay, which acts as FixedUpdate. The solution would be to move this code into coroutine-turned OnTriggerEnter. So basically, it could look like that:

private IEnumerator OnTriggerEnter(Collider other)
{
	while(true) 
	{
		// here's your code from OnTriggerStay
		yield return null;
	}
}

As you can see, when coroutine version of OnTriggerEnter yields “null”, it acts as Update. And, here’s your script after modifications. It should now work as you want:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightsOnPress : MonoBehaviour
{
	public AudioSource Click;
	public Light Lights;
	public GameObject Text;
	public bool LightisOn;

	public void Start()
	{
	LightisOn = Lights.enabled = false;
	}

	IEnumerator OnTriggerEnter(Collider other)
	{
		Text.gameObject.SetActive(true);

		while (true)
		{
			if (Input.GetKeyDown("e"))
			{
				if (LightisOn)
				{
					LightisOn = Lights.enabled = false;
					Click.Play();
				}
				else
				{
					LightisOn = Lights.enabled = true;
					Click.Play();
				}
			}
			yield return null;
		}
	}

	void OnTriggerExit(Collider other)
	{
		Text.gameObject.SetActive(false);
	}
}