Search Unity

OnTriggerStay mouse button response

Discussion in 'Scripting' started by Alex_R, Apr 4, 2008.

  1. Alex_R

    Alex_R

    Joined:
    May 13, 2007
    Posts:
    35
    Hi!!

    I have a little problem with this function attached to a mesh trigger.

    Code (csharp):
    1. function OnTriggerStay() {
    2.     if (Input.GetButtonDown ("Fire1")) {
    3.         icono.enabled=false; // this is a GUI texture
    4.         Destroy (this);
    5.         }
    6. }
    This works but not fine. When I press the mouse boutton the "icono" GUI texture disapears. But I don't understand why I need sometimes to press 3 or 4 times the button to activate the script.
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    This is because OnTriggerStay is on the physics timer, like FixedUpdate, as compared to Update. So it won't necessarily run every frame, and thus functions which return true for one frame (like GetButtonDown) might not return true when OnTriggerStay runs.

    A few ways to solve this...the simplest is, you might be able to use GetButton instead of GetButtonDown. Since that returns true every frame the button is down, it's guaranteed to work during FixedUpdate. (Well, unless you click really fast.)

    If GetButton isn't feasible, then you can do something like

    Code (csharp):
    1. private var inTrigger = false;
    2.  
    3. function OnTriggerEnter() {
    4.    inTrigger = true;
    5. }
    6.  
    7. function OnTriggerExit() {
    8.    inTrigger = false;
    9. }
    10.  
    11. function Update() {
    12.    if (Input.GetButtonDown ("Fire1")  inTrigger) {
    13.       icono.enabled=false; // this is a GUI texture
    14.       Destroy (this);
    15.       }
    16. }
    --Eric
     
  3. Alex_R

    Alex_R

    Joined:
    May 13, 2007
    Posts:
    35
    Thanks Eric, very useful your replay!!!!! :D