0
\$\begingroup\$

I have a UI button. I want a function to be called whenever I press a specific key on my keyboard while my mouse is hovering over the button. I want to make something similar to UI in Ark SE where you can press 'T' while hovering over an item in your inventory to transfer it.

The button component OnClick() has not received keypress input, only mouse clicks.

I am using the New Unity Input System

I have tried using a Raycast from ScreenPointToRay however this did not work as I do not have colliders on my UI and it is part of a Canvas.

\$\endgroup\$
1
\$\begingroup\$

I found a solution. I don't think it would be the best but it works for now. With the new input system I subscribe A function (OnTransferKey) to a Key Press

void OnEnable() {
    uI_Manager.uIInputManager.Inventory.OnTransfer.performed += OnTransferKey;
}

void OnDisable() {
    uI_Manager.uIInputManager.Inventory.OnTransfer.performed -= OnTransferKey;
}

In the OnTransferKey function I check if the mouse is hovering over the gameObject

    bool MouseOverSelf() {
    return EventSystem.current.IsPointerOverGameObject();
}


void OnTransferKey(InputAction.CallbackContext obj) {

    if (MouseOverSelf()) {
        print("Do Transfer");
    }
}

This works for me for now. Remember to add using UnityEngine.EventSystems;

\$\endgroup\$
0
\$\begingroup\$

I don't know much about the New Unity Input System, but you don't need colliders on your UI objects to raycast them, you just need a Graphic Raycaster component on the canvas, then make sure that the things you want to raycast have the "Raycast Target" box checked like so: image component with Raycast Target checked

And then the scripting info you need is here in Unity's docs. That should be all you need let me know if I can help anymore.

\$\endgroup\$
2
  • \$\begingroup\$ This doesn't appear to answer the part about calling specific functions when particular keyboard keys are pressed while the mouse is over a button. \$\endgroup\$
    – DMGregory
    Jul 29 at 9:21
  • \$\begingroup\$ In the Unity docs I linked, it includes a script where all you need to do is swap out the key it uses for the key you want to use. I was originally gonna write it out but I realized the docs said it better. \$\endgroup\$
    – Tristan367
    Jul 29 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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