On/Off Trigger is making Light Flicker

So I found a great script to make the doors open and close on here, and I combined it with other scripts (learning from them the whole time) to make a simple apartment where I can open and close the fridge and freezer doors and open and close the bathroom door.

Feeling adventurous, I moved on to trying to turn the light on and off. Much scrabbling and whining later, I’ve got it to at least acknowledge that when I hover my reticle over the light and click the mouse button, it toggles to “off”.

Except instead of turning off, it’s flickering. I checked and it’s turning on and off until I click again, and I’m honestly not sure what I missed. So! Here’s my code:

public bool on = true;

public void ChangeLightState()
{
	on = !on;
}
void Update () {
	
	if(on) //on == true
	{
		GetComponent<Light>().enabled = GetComponent<Light>().enabled;
	}
	else
	{
		GetComponent<Light>().enabled = !GetComponent<Light>().enabled;
	}
}

That’s the code I put on the light itself. My Interact Script is:

void Update () {

	if(Input.GetKeyDown(KeyCode.Mouse0))
	{
		Ray ray = new Ray(transform.position, transform.forward);
		RaycastHit hit; 
	if(Physics.Raycast(ray, out hit, interactDistance))
		if(hit.collider.CompareTag("Door"))
	{
		hit.collider.transform.parent.GetComponent<DoorScript>().ChangeDoorState();
	}
		if(hit.collider.CompareTag("Light"))
	{
			hit.collider.transform.GetComponent<ToggleLight>().ChangeLightState();
	}
}

I’m missing something super obvious, right?

ETA: Also, is there a way to turn emissions off/on instead of light?

What’s happening is that when on is false, you’re executing the else part of your if statement in Update. That is toggling the light on and off. You don’t really need to do the light toggling in Update, just toggle it directly in ChangeLightState.

I would change the function name to ToggleLightState

public void ToggleLightState()
{
  GetComponent<Light>().enabled = !GetComponent<Light>().enabled;
}

Remove the code from Update, and just call the new function like you do now.

Also, if you want to be a little more efficient you can eliminate one of the GetComponent calls…

public void ToggleLightState()
{
  Light light = GetComponent<Light>();
  light.enabled = !light.enabled;
}

You could also cache the light variable in the class and get the instance in the Start method so you don’t have to call GetComponent during normal game play. However, this particular function isn’t something that would be called often, so the optimization really isn’t necessary. It’s still considered good practice to minimize those GetComponent calls though.