Created
December 7, 2022 14:16
-
-
Save mrkybe/a24b66fe674d2e99daeed66d13cedd11 to your computer and use it in GitHub Desktop.
Unity Input Controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.InputSystem; | |
public enum ControlMode { MOUSEANDKEYBOARD, CONTROLLER } | |
public class ControlFreak : MonoBehaviour | |
{ | |
public static ControlFreak Instance { get; private set; } | |
public static DefaultControls Controls { get; private set; } | |
public ControlMode ControlMode = ControlMode.MOUSEANDKEYBOARD; | |
public static Vector3 MousePositionWorld { get; private set; } | |
private void Awake() | |
{ | |
if (Instance == null) | |
{ | |
Instance = this; | |
} | |
else | |
{ | |
Debug.LogError("Can't have two control freaks"); | |
} | |
if (Controls == null) | |
{ | |
Controls = new DefaultControls(); | |
} | |
else | |
{ | |
Debug.LogError("Tried to reinitialize controls"); | |
} | |
Controls.Cursor2DControls.Position.performed += Position_performed; | |
Controls.DevControls.ToggleControlScheme.performed += ToggleControlScheme_performed; | |
} | |
private void Position_performed(InputAction.CallbackContext obj) | |
{ | |
var mp = obj.ReadValue<Vector2>(); | |
MousePositionWorld = mp.ToV3XZ(); | |
} | |
private void ToggleControlScheme_performed(InputAction.CallbackContext obj) | |
{ | |
switch (ControlMode) | |
{ | |
case ControlMode.MOUSEANDKEYBOARD: | |
UsingXboxController(); | |
break; | |
case ControlMode.CONTROLLER: | |
UsingMouseAndKeyboard(); | |
break; | |
} | |
} | |
private void Start() | |
{ | |
switch (ControlMode) | |
{ | |
case ControlMode.MOUSEANDKEYBOARD: | |
UsingMouseAndKeyboard(); | |
break; | |
case ControlMode.CONTROLLER: | |
UsingXboxController(); | |
break; | |
} | |
} | |
public static ControlMode GetCurrentControlMode() | |
{ | |
return Instance.ControlMode; | |
} | |
public static void UsingMouseAndKeyboard() | |
{ | |
Controls.bindingMask = InputBinding.MaskByGroup(Controls.MouseAndKeyboardScheme.bindingGroup); | |
Instance.ControlMode = ControlMode.MOUSEANDKEYBOARD; | |
} | |
public static void UsingXboxController() | |
{ | |
Controls.bindingMask = InputBinding.MaskByGroup(Controls.XboxControllerScheme.bindingGroup); | |
Instance.ControlMode = ControlMode.CONTROLLER; | |
} | |
private void OnEnable() | |
{ | |
Controls.Enable(); | |
} | |
private void OnDisable() | |
{ | |
Controls.Disable(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment