Help with light Switch Script

Hi guys, I’ve been making a switch script, the idea is when player in the collider can press key to turn on and off lights (with sound) but my script doesn’t works, here is the script , thanks and sorry for my english

 var luz : GameObject ;

 var Volume : float = 0.5;

 function Start () {
audio.volume = Volume;
}

function Update () {
 
if(Input.GetKeyUp(KeyCode.E))
 
{
        
        luz.active = true;
        audio.Play();
}
 
else if(Input.GetKeyUp(KeyCode.E))
 
{
       
        luz.active = false;
}
 
 
}


function OnTriggerEnter (other : Collider)
{
        if(other.gameObject.tag == "Player")
        {
                luz.active = true;
        }
}
 
function OnTriggerExit (other : Collider)
{
        if(other.gameObject.tag == "Player")
        {
                luz.active = false;
        }
}

There seem to be a number of issues here: you call the condition if(Input.GetKeyUp(KeyCode.E)) twice, which won’t trigger properly, the better ‘if’ would be

if(Input.GetKeyUp(KeyCode.E))
{if(luz.active == true)){   
        luz.active = true;
        audio.Play();

}else {
luz.active = false;
}
}

Remove the second bit of code and check whether the lightswitch turns off and on no matter how close you are.

Now, instead of having the collider also affect the state directly, use it just to enable the function above. E.G.

function OnTriggerEnter (other : Collider)
{
        if(other.gameObject.tag == "Player")
        {
           closeEnough=true;
        }
}
 
function OnTriggerExit (other : Collider)
{
        if(other.gameObject.tag == "Player")
        {
           closeEnough=false;
        }
}

and change your above function to check for the closeEnough bool.

if(Input.GetKeyUp(KeyCode.E))
{if(luz.active == true && closeEnough==true)){   
        luz.active = true;
        audio.Play();

}else {
luz.active = false;
}
}