Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

How to check the device type of the last input

Discussion in 'Input System' started by arvzg, Aug 2, 2020.

  1. arvzg


    Jun 28, 2009
    Hey guys, I'm looking for a way to switch my Input handling code depending on the type of controller you're using. If you're using Mouse&Keyboard I want to handle input for example using
    void MouseLook(Vector2) 
    method, and with Gamepad, I want to use
    void GamepadLook(Vector2) 
    , and I want the player to be able to switch inputs seamlessly, so I need to know the last input's controller type.

    What's the best way to do this?
  2. Rene-Damm


    Unity Technologies

    Sep 15, 2012
    In general, the recommended way is to use control schemes. I.e. to add one control scheme for mouse&keyboard and one for gamepad (similar to how it's done with the default actions you get when you click the "Create Actions..." button in the PlayerInput component inspector).

    With this, you can query the current control scheme from PlayerInput and receive a notification when the user switches from one control scheme to another.
  3. arvzg


    Jun 28, 2009
    @Rene-Damm I am actually already using Control Schemes, one for Gamepad and one for Keyboard&Mouse, however I am not using the PlayerInput component, instead I'm using the generated C# class directly

    One way I've been able to figure out how to do it is by subscribing to the performed event of each Action. So I have a MouseLook action and a GamepadLook action.

    Code (CSharp):
    1. void Awake()
    2. {
    3.     _actions = new MyActions();
    4.     _actions.Player.GamepadLook.performed += OnGamepadLookPerformed;
    5.     _actions.Player.MouseLook.performed += OnMouseLookPerformed;
    6. }
    8. void OnMouseLookPerformed(InputAction.CallbackContext context)
    9. {
    10.     _currentControllerType = ControllerType.MouseKeyboard;
    11. }
    13. void OnGamepadLookPerformed(InputAction.CallbackContext context)
    14. {
    15.     _currentControllerType = ControllerType.Gamepad;
    16. }
    But maybe it's not the most efficient way of doing it as this method gets called many times over and over again every time you perform the action, is there any other way?