- Home /
Press multiple switches to unlock the door
I made 2 scripts, one that is a switcher and one that checks if object is switched (Switch, SwitchCheck).
Switch script (it's on 2 objects that are switches and both objects have colliders with IsTrigger checked):
public var IsPressed : boolean = false;
function OnTriggerStay (){
if (Input.GetKeyDown(KeyCode.JoystickButton1)){
IsPressed = true;
Debug.Log("Switch activated");
}
}
SwitchCheck script (it's on door that should be opened)
public var Switch1 : Switch;
public var Switch2 : Switch;
function Update()
{
if (Switch1.IsPressed && Switch2.IsPressed)
{
Destroy (gameObject);
}
}
Now, he problem here is, that it "does" kind of work...after I press the button like 20 times. My question is, did I write something wrong?
EDIT: I found the answer...You should not use GetKeyDown inside the OnTriggerStay. It should only be called from the Update method. Therefore, you need to implement OnTriggerEnter and OnTriggerExit to check whether the condition is satisfied or not by holding a flag something like 'triggered'. Inside the Update method of Switch1 and Switch2, you need to check the flag; if it is true, then, you get the input.
public var IsPressed : boolean = false;
public var triggered : boolean = false;
function OnTriggerEnter() { triggered= true; }
function OnTriggerExit() { triggered= false;}
function Update()
{
if (triggered & Input.GetKeyDown(KeyCode.JoystickButton1))
IsPressed = true;
}
Have you tested if the problem is on the input or collider? You could test it like this:
function Update (){
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.JoystickButton1))
Debug.Log("Input works!");
}
function OnTriggerStay (){
Debug.Log("Collision works!");
}
Just a thought
Your answer
Follow this Question
Related Questions
Else and If 2 Answers
Boolean wont acitvate if the enemy enters a trigger 1 Answer
Play a simple animation once on key press 3 Answers
displaying playerprefs 1 Answer
Why does it seem like my boolean is true and false 0 Answers