Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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;     
}
share|improve this answer
    
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; –  Samurai Fox Jul 27 at 17:40
    
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). –  Alican Jul 27 at 18:03
    
well then...ok gonna do it your way/ unity way and not cause myself anymore future problems –  Samurai Fox Jul 27 at 18:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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