Search Unity

Button Held Down

Discussion in 'UGUI & TextMesh Pro' started by RobertFitzgibbon, Mar 2, 2015.

  1. RobertFitzgibbon

    RobertFitzgibbon

    Joined:
    Mar 2, 2015
    Posts:
    32
    First off, let me say sorry if I missed a post explaining how to do this. I've been looking for seriously about 3 hours straight for a solution.

    I need to create a script for a UI button that will repeat a function as the button is held down. For example a shoot function. I can't have it so the player has to spam the button to shoot a gun. I've seen solutions that include,

    if (Rect.draw

    and stuff like that but I don't want a button to draw at runtime. I already have my whole UI setup, so that's not really an option. I just need a script that I can attach to an already made button in the editor.

    Can anyone help? Again, sorry in advance if I missed the answer.
     
  2. RobertFitzgibbon

    RobertFitzgibbon

    Joined:
    Mar 2, 2015
    Posts:
    32
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    To do something every frame, put it in the Update() method.

    To know when the user starts and stops pushing a button, have the button react to the PointerDown and PointerUp events. You can do that through the editor by adding an EventTrigger component to your object, or you can create your own component that implements the IPointerDown and IPointerUp interfaces.

    Set a flag when a PointerDown happens; unset that flag when a PointerUp happens.

    In your Update() method, check whether the flag is set, and then act appropriately.
     
    RobertFitzgibbon likes this.
  4. RobertFitzgibbon

    RobertFitzgibbon

    Joined:
    Mar 2, 2015
    Posts:
    32
    Thank you so much it works great! Wow that was way easier than I had thought it was going to be.