Search Unity

Resolved Access button functionality via script

Discussion in 'Editor & General Support' started by xDayhawk, Mar 31, 2021.

  1. xDayhawk

    xDayhawk

    Joined:
    Jun 24, 2020
    Posts:
    57
    Hi,

    I have an object with a button it, and it has different images or colors selected for each action, hover, selected, pressed etc'
    it works great when i'm using my mouse and on mobile, however - i would like the option to use the exact same button functionality when using a keyboard.

    what i mean is - if i press "W" i want it to simulate and show the exact same thing as when i press the button that marks left, same for other buttons... i hope that's clear.

    to clarify - is there anyway to do the following from a script:
    when i press "W", i want it to be exactly the same as what happens when i press on a button, whatever is in the pressed or selected part?
    i dont want it to activate the OnClick part of the button, i just want the button UI changes.
    (i know i can do something from code, but i dont want to duplicate, i want to call the exact same thing in case i change it in the future)


    Thanks in advance,
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Generally break up the steps of this:

    - collect ALL user intention:
    ---------> button press
    ---------> related key press (W)

    - act upon the user's intention

    It's trivial to add a script that invokes the Button's .onClick() method when you press a key. Such a script would look something like:

    https://github.com/kurtdekker/datas...Assets/Datasack/Input/DSUserIntentKeyboard.cs

    That's a more-involved fully-featured script to map any number of keyboard input events down to invoking a button, but the meat and potatoes is lines 121 and 122:

    Code (csharp):
    1.                var button = GetComponent<Button>();
    2.                button.onClick.Invoke();
     
  3. xDayhawk

    xDayhawk

    Joined:
    Jun 24, 2020
    Posts:
    57
    @Kurt-Dekker thank you for your answer.
    i took your advice and just broke it all down, it seems like a lot of work to do if i want to support both keyboard and mouse pointers / mobile.
    really thought there would be something shorter / easier.

    i dont need the onClick.Invoke though.

    thanks again!
     
    Kurt-Dekker likes this.