Toggle variable

When the player stay inside the trigger and press the button ‘E’ I want to make some action and toggle variable isHeaterOn.

I can’t understand why, but in my code if and else always work together and no matter if isHeaterOn equals true or false.

In this case when I press E one time, i have message in the console:

off → on

on → off

Why it happens?

if(Input.GetKeyDown(KeyCode.E))
{
    if(!isHeaterOn)
    {
	    Debug.Log("off -> on");
	    heater.SetActive(true);
	    isHeaterOn = true;
    }
	else
	{
	    Debug.Log("on -> off");
	    heater.SetActive(false);
	    isHeaterOn = false;
	}
}

Edit1:

void OnGUI()
	{
		if(isInsideTrigger)
			switch(numberOfTrigger)
			{			
			case 13:		        
				if(Input.GetKeyDown(KeyCode.E))
				{
					if(!isHeaterOn)
					{
						Debug.Log("off -> on");
						heater.SetActive(true);
						isHeaterOn = true;
					}
					else
					{
						Debug.Log("on -> off");
						heater.SetActive(false);
						isHeaterOn = false;
					}					
				}
				break;
          //...

The issue is that you have your code inside of OnGUI. You should not place Input code inside of OnGUI. OnGUI can be called more than once per frame. In your case, you are simply seeing on GUI called twice.

This code should be in your Update loop, it has no business in OnGUI. If you absolutely need to use key strokes inside of OnGUI, see this answer.

This code is in OnGUI ()? That’s your problem then. Move it to Update().

OnGUI is called multiple times per frame - once for layout and again for painting, which is why your code is toggling on and off. It should only be used for GUI. Game logic should be in Update().

if you code like this

void OnGUI()
{
 if(Input.GetKeyDown(KeyCode.E))
 {
     if(!isHeaterOn)
     {
         Debug.Log("off -> on");
         heater.SetActive(true);
         isHeaterOn = true;
     }
     else
     {
         Debug.Log("on -> off");
         heater.SetActive(false);
         isHeaterOn = false;
     }
 }
}