- Home /
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;
}
}
If the idea is "in the collider" why not use OnTriggerStay?
Answer by tobyfee · Mar 14, 2014 at 10:14 PM
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; } }
The another "$$anonymous$$i"Script that i have does't work either, i can't understand
var luz : GameObject ;
function OnTriggerStay (other : Collider){
if (Input.Get$$anonymous$$eyDown("e"))
luz.enable = true ;
}
function OnTriggerExit (other : Collider) {
if (Input.Get$$anonymous$$eyDown("e"))
luz.enable = false ;
}
Dont post a follow-up as ANOTHER answer as you did here, I converted this one for you. You will in all likelyhood not be able to spam the E button in the millisecond or so of the enter/exit firing, don't put that stuff there, ever.
In your OnTriggerStay, add new line
print("Trigger fire for "+other.name);
ensure you are getting the TriggerEvent you are expecting.