Advertisement
jefflynch

Untitled

Jun 14th, 2025
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.InputSystem;
  4.  
  5. namespace _Project.Core.Input
  6. {
  7.     public class InputDeviceSwapController : Single<InputDeviceSwapController>
  8.     {
  9.         public enum ControlScheme { MouseAndKeyboard, Gamepad }
  10.  
  11.         public static event EventHandler OnGamepadUnused;
  12.         public static event EventHandler OnGamepadUsed;
  13.        
  14.        
  15.  
  16.         [field: SerializeField] public ControlScheme MyControlScheme { get; set; }
  17.         [field: SerializeField] public bool IsCursorVisible { get; set; }
  18.    
  19.         private void OnEnable() => RegisterDeviceSwap();
  20.  
  21.         private void RegisterDeviceSwap() => InputSystem.onActionChange += HandleInputSystemOnActionChange;
  22.  
  23.         private void HandleInputSystemOnActionChange(object obj, InputActionChange change)
  24.         {
  25.             if (change == InputActionChange.ActionStarted)
  26.             {
  27.                 var inputAction = (InputAction) obj;
  28.                 var lastControl = inputAction.activeControl;
  29.                 var lastDevice = lastControl.device;
  30.                 if (lastDevice == Gamepad.current)
  31.                 {
  32.                     //Using GamePad
  33.                     MyControlScheme = ControlScheme.Gamepad;
  34.                     OnGamepadUsed?.Invoke(this, EventArgs.Empty);
  35.                     Cursor.visible = false;
  36.                 }
  37.                 else if (lastDevice == Keyboard.current || lastDevice == Mouse.current)
  38.                 {
  39.                     //Using Mouse & Keyboard
  40.                     MyControlScheme = ControlScheme.MouseAndKeyboard;
  41.                     OnGamepadUnused?.Invoke(this, EventArgs.Empty);
  42.                     Cursor.visible = IsCursorVisible;
  43.                 }
  44.  
  45.                 //Debug.Log($"device: {lastDevice.displayName}");
  46.             }
  47.         }
  48.        
  49.         public static bool IsUsingGamepad() => Get.MyControlScheme == ControlScheme.Gamepad;
  50.         public static bool IsUsingMouseAndKeyboard() => Get.MyControlScheme == ControlScheme.MouseAndKeyboard;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement