Search Unity

How Do I Detect When A Button is Being Pressed & Held On - EventType

Discussion in 'Scripting' started by ExbowFTW, Sep 4, 2015.

Thread Status:
Not open for further replies.
  1. ExbowFTW

    ExbowFTW

    Joined:
    May 2, 2015
    Posts:
    281
    Is there an event type that detects when a button is being pressed down - NOT clicked on?

    Is there also a way to detect when the button is let go?
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    This is typically done by detecting the mouse down and mouse up separately. If you are between mouse down and mouse up then the button is held down.
     
    ngerbens and Pawli like this.
  3. Lentaq

    Lentaq

    Joined:
    Apr 8, 2015
    Posts:
    57
    I'm not sure if you are referring to mouse buttons being held vs. clicked or keyboard buttons?

    For key presses:
    http://docs.unity3d.com/ScriptReference/Input.GetKey.html
    http://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
    http://docs.unity3d.com/ScriptReference/Input.GetKeyUp.html

    If you are referring to GUI/UI(in game menus and such) buttons and not peripherals(keyboard/mouse/joystick), then that's a different story. Need more details about what you are referring to.

    List of mouse + "mouse over GUI" stuff:
    http://docs.unity3d.com/ScriptReference/30_search.html?q=onmouse
     
  4. ExbowFTW

    ExbowFTW

    Joined:
    May 2, 2015
    Posts:
    281
    I mean GUI/UI button. Here's the difference between held vs. clicked:

    UI Buttons have a Button Component which has a public function called OnClick(). This is triggered whenever the user clicks down on the button using his/her mouse during THAT frame. After that frame, if you are still holding down on your mouse, it does not detect it. It is kind of like GetKeyDown, but for buttons.

    I'm trying to find an EventType, or some sort of function (for C#) like GetKey, but for buttons. GetKey returns true whenever the key is being held down - so every frame that the key is down, it returns true. I'm trying to find a GetKey() function, but for a UI Button - every frame that the mouse is down over the button, it returns true.

    Hope that makes sense - It's a pretty simple analogy: Buttons to Keys.

    Thanks!
     
  5. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Something like this should work :
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.EventSystems;
    4.  
    5. public class MyButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
    6.  
    7. public bool buttonPressed;
    8.  
    9. public void OnPointerDown(PointerEventData eventData){
    10.      buttonPressed = true;
    11. }
    12.  
    13. public void OnPointerUp(PointerEventData eventData){
    14.     buttonPressed = false;
    15. }
    16. }
     
  6. ExbowFTW

    ExbowFTW

    Joined:
    May 2, 2015
    Posts:
    281
    Ooh okay ;) Let me try it out. Thanks :D
     
    Krishna017 likes this.
  7. ExbowFTW

    ExbowFTW

    Joined:
    May 2, 2015
    Posts:
    281
    IT WORKS! Thanks so much! I've been looking for a solution for over a week!

    BTW: What does IPointerDownHandler and IPointerUpHandler do to the script?
     
  8. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Cool, glad I could help.

    They basically allow you to receive "OnPointerUp" & "OnPointerDown" callbacks.
     
  9. ExbowFTW

    ExbowFTW

    Joined:
    May 2, 2015
    Posts:
    281
    Ah. That's why whenever I tried using that before, it never worked ;)

    Also: I have another question: (I dunno if you know this, but)

    I'm thinking of making a "Daily Challenge", where every day (Exactly 24 hours) it gives you a new challenge that you have to do. How do I find the actual real time. And I don't mean system time - otherwise they could cheat and always just set the time on their phone so that the game gives them the challenge sooner.
     
  10. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Only way I can think of right now is using "System.DateTime.Now".

    Maybe a few google searches will get you the answer you need.
     
    Krishna017 likes this.
  11. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Typically you will need to use the www class to get the current time off the server. Nothing on the client should be trusted.
     
    Westland likes this.
  12. ExbowFTW

    ExbowFTW

    Joined:
    May 2, 2015
    Posts:
    281
    Yeah, okay. Thanks!
     
  13. MisterSkitz

    MisterSkitz

    Joined:
    Sep 2, 2015
    Posts:
    833
    Just curious. Does this work for android touches as well?
     
  14. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Yes.
     
    Krishna017 likes this.
  15. Diwill13

    Diwill13

    Joined:
    Dec 15, 2019
    Posts:
    1
    Hey, so the script works, but where do I have to put it ? OnClick, Event trigger...?
     
    aymusbond likes this.
  16. joseGuate97

    joseGuate97

    Joined:
    Mar 1, 2018
    Posts:
    57
    This was such an excellent script. Thank you.

    Using UnityEvents and coroutines, I came up with these additions to track how much time is pressed and trigger an action after a certain amount of seconds is hit, which was what I needed.

    Hopefully someone else will find it useful too. I called it "PressDetector," so you may attach it to any button separately and start tracking the time being pressed :)

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.EventSystems;
    4. using UnityEngine.Events;
    5.  
    6. public class PressDetector : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    7. {
    8.     [Range(1.0f, 10.0f)]
    9.     public float seconds = 1.0f;
    10.     public UnityEvent onPressedOverSeconds;
    11.  
    12.  
    13.     public void OnPointerDown(PointerEventData eventData)
    14.     {
    15.      
    16.         StartCoroutine(TrackTimePressed());
    17.     }
    18.  
    19.     public void OnPointerUp(PointerEventData eventData)
    20.     {
    21.      
    22.         StopAllCoroutines();
    23.     }
    24.  
    25.     private IEnumerator TrackTimePressed()
    26.     {
    27.         float time = 0;
    28.  
    29.  
    30.         while (time < this.seconds)
    31.         {
    32.             time += Time.deltaTime;
    33.             yield return null;
    34.         }
    35.  
    36.         onPressedOverSeconds.Invoke();
    37.     }
    38.  
    39. }
     
  17. BluNyte

    BluNyte

    Joined:
    Aug 2, 2020
    Posts:
    1
    On the Button you are trying to catch input from.
    after that you can reference that button from anywhere.
     
  18. GRPro

    GRPro

    Joined:
    Jun 26, 2021
    Posts:
    1
    Just did this and it works great!!!!! :)
     
  19. GerorgeCotuna

    GerorgeCotuna

    Joined:
    Feb 10, 2020
    Posts:
    2
    Great topic Helped me a lot, i was stuck for a week!
     
  20. ngerbens

    ngerbens

    Joined:
    Nov 20, 2017
    Posts:
    33
    I was also looking for the magical 'GetButtonBeingHeldDown' function. But this answer makes me realize I'm not using my brain enough. So Simple. Thank you.
     
    Krishna017 likes this.
  21. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,999
    Since this thread was already bumped, I'd like to clear up some confusion that many people seem to have:

    That's not how a click works in pretty much any UI system. A "click" is actually more complex. First of all a click usually fires when the mouse button is released, not when it's pressed down. Also a click usually has additional requirements. For UI elements that usually means that the mouse button up event happened on the same element as the mouse button down event, otherwise no click would be produced. Some frameworks even consider a max mouse delta between the down and up events. So when the mouse is moved too far, no click is produced. Though usually for ordinary buttons you can press down on the left side and release on the right side and it would be a click. Though a good counterexample are web browsers / websites and links. They usually have a max move delta. Feel free to try it out. Try pressing on any link and hold the mouse down. The link wont open. When you move the mouse with the held down button you usually initiate a drag event once you move a certain distance. A click is only generated when you press down and relase the button at the same spot (with an error margin since you usually can't hold your mouse perfectly stationary during a mouse down).

    Almost any UI system allows to cancel / prevent a click when you press down on a button and then simply move off the button while the mouse is down. When you relase outside the button, no click is generated. Most drop down menus are often considered one element. Pressing down on one menu item but releasing on another would usually trigger the element you relased the mouse on. Though there are menus which would cancel the action.

    It's also almost impossible to press down the mouse button for just "one frame". Any click usually does have a holding period between the down and up events. Yes, if a button or UI element should carry out a different action when "holding" down the mouse, you always have to specify a certain time threshold to differentiate between a click or another action. Android smartphone homescreen icons usually initiate a "move" when you hold down on an item for a certain amount of time without moving. However pressing and holding down and moving immediately does not even cause a down event as this usually would enter scroll / pan mode of the screen or list view. Such UI interactions can get quite complicated. It's essentially a quite complex statemachine that has various trigger conditions and time delays.

    If you're thinking about UI design, you should analyse existing UIs carefully. What time and distance threshold makes sense / feel intuitive. Those values are usually different when working on a touch screen compared to a mouse interaction.

    Note that keyboard input is handled different. Here it usually causes an immediate action on the down event. This is of course because when holding down a key we usually get a repeated keypress based on the repeat rate configured in the OS.
     
    Krishna017 likes this.
  22. andrewhyun

    andrewhyun

    Joined:
    Oct 5, 2019
    Posts:
    1
    Thank you so much for the MyButton Script!
     
  23. Logan1112

    Logan1112

    Joined:
    Aug 30, 2022
    Posts:
    1
    Why doesn't this work

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.EventSystems;
    5. using UnityEngine.Events;
    6. public class ButtonPressed : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
    7. {
    8. public GameObject camera;
    9. public GameObject player;
    10. public bool buttonPressed;
    11.  
    12. public void Start()
    13. {
    14.     buttonPressed = false;
    15. }
    16. public void OnPointerDown(PointerEventData eventData)
    17. {
    18.     buttonPressed = true;
    19. }
    20. public void OnPointerUp(PointerEventData eventData)
    21. {
    22.     buttonPressed = false;
    23. }
    24.  
    25. void Update()
    26. {
    27.     if(buttonPressed = true)
    28.     {
    29.         camera.transform.position = player.transform.position + new Vector3(0, 1, -5);
    30.         buttonPressed = false;
    31.     }
    32. }
    33. }
     
  24. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    Please don't necro-post to 2015 threads, especially with incomplete questions.

    Start your own thread. It's FREE! When you post, keep this in mind:

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)
     
    inyourpc and Bunny83 like this.
Thread Status:
Not open for further replies.