0
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

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;     
}
|improve this answer|||||
\$\endgroup\$
  • \$\begingroup\$ Thanks! That worked like a charm. I just don't understand why it doesn't work(my script)...because in this next script it works just fine: var script1: Portal1; function OnTriggerStay (){ if (Input.GetKeyDown(KeyCode.JoystickButton1)){ GameObject.Find("gate_big").GetComponent(Portal1); script1.enabled = true; \$\endgroup\$ – Samurai Fox Jul 27 '14 at 17:40
  • \$\begingroup\$ In the documentation, it is stated that this method needs to be called from Update. I don't know the internal structure of Unity, so can't help you there. I guess, input management is synchronized with graphics rather than physics (collision/trigger). \$\endgroup\$ – Alican Jul 27 '14 at 18:03
  • \$\begingroup\$ well then...ok gonna do it your way/ unity way and not cause myself anymore future problems \$\endgroup\$ – Samurai Fox Jul 27 '14 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.