colorful stone mosaic

How to handle mouse clicks with the new input system

The new input system is very flexible and allows complex setups for different devices. In larger projects there is usually an intermediate layer to handle user input properly. But sometimes all you want is handling a simple mouse click on a game object.

In the examples, I listen to the right mouse click e.g. to open a context menu. The game object has a collider attached.

Solution 1: IPointClickEventHandler

This solution works for the new and the old input system. It requires some prerequisites in the scene:

  • Create an event system if not existing yet: Right click in the Hierarchy view > UI (Canvas) > EventSystem
  • Add a PhysicsRaycaster to the camera – either in the scene or by script.
  • Implement the interface IPointerClickHandler in a MonoBehaviour and assign it to the clickable object.
public class ContextMenu : MonoBehaviour, IPointerClickHandler
{   
    private void Start()
    {
        // add physics raycaster if it doesn't exist yet
        var camera = Camera.main;
        if (camera != null && !camera.TryGetComponent<PhysicsRaycaster>(out var raycaster))
        {
            camera.gameObject.AddComponent<PhysicsRaycaster>();
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        Debug.Log("OnPointerClick");
    }
}
 

Solution 2: Input Action

The second option makes use of an input action and thus works only with the new input system. PhysicsRaycaster and EventSystem are not necessary for this implementation.

The input action can be defined like this.

Input Actions in the Unity editor. "Right Button [Mouse]" is selected within the Action "ContextMenu".

In the following code, the input action is defined in the project-wide actions. It is looked up by it’s name.

public class ContextMenu : MonoBehaviour
{
    InputAction m_openAction;
    private void Start()
    {
        m_openAction = InputSystem.actions.FindAction("ContextMenu");
        m_openAction.performed += OpenContextMenu;
    }
    
    private void OnDestroy()
    {
        m_openAction.performed -= OpenContextMenu;
    }

    private void OpenContextMenu(InputAction.CallbackContext context)
    {
        Debug.Log("OnPointerClick");
    }

}

Alternatively, you can add a reference directly to the InputAction instead of looking it up in the action map.

public class ContextMenu : MonoBehaviour
{
    [SerializeField] 
    private InputActionReference m_openAction;
    private void Start()
    {
        m_openAction.action.performed += OpenContextMenu;
    }

    // same code as above 
    ...
}

Prev
Hand tracking

Hand tracking

Hand tracking allows you to interact with a VR environment without separate

Next
XR Interaction Toolkit

XR Interaction Toolkit

The XR Interaction Toolkit is a Unity package that provides high-level