Skip to content

Instantly share code, notes, and snippets.

@MccDev260
Last active March 25, 2024 16:12
Show Gist options
  • Save MccDev260/b6ea75bfc6a53d0f5d99571a5de37385 to your computer and use it in GitHub Desktop.
Save MccDev260/b6ea75bfc6a53d0f5d99571a5de37385 to your computer and use it in GitHub Desktop.
Unity Input System: Get the type of input device the player is currently using.
using System;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.DualShock;
using UnityEngine.InputSystem.XInput;
// Hope this helps someone navigate the mess that is Unitys Input System.
namespace MccDev260.InputDevices
{
/// <summary>
/// Possible input types you want to account for.
/// </summary>
[Serializable]
public enum InputDeviceType
{
PC,
Playstation,
Xbox,
}
/// <summary>
/// Example script that returns the type of input device last used by the player.
/// </summary>
/// <remarks>
/// Note: This is for use with Unitys 'new' Input System package.
/// </remarks>
public class GetInputDeviceType : MonoBehaviour
{
[SerializeField] private InputActionAsset actionsAsset;
[SerializeField] private InputDeviceType currentInputDevice = InputDeviceType.PC;
/// <summary>
/// Returns the device type the player is currently using.
/// </summary>
public InputDeviceType GetCurrentDevice { get { return currentInputDevice; } }
private void OnEnable()
{
// Setup a callback thats triggered each time a bound input is used.
foreach (InputActionMap map in actionsAsset.actionMaps)
{
map.actionTriggered += OnActionTriggered;
}
}
private void OnDisable()
{
// Remove callback when object is disabled to free up memory.
foreach (InputActionMap map in actionsAsset.actionMaps)
{
map.actionTriggered -= OnActionTriggered;
}
}
private void OnActionTriggered(InputAction.CallbackContext obj)
{
SetCurrentDeviceType(obj.control.device);
}
private void SetCurrentDeviceType(InputDevice device)
{
switch (device)
{
case Gamepad:
if (device is DualShockGamepad)
{
Debug.Log("Last used device is a Playstation Controller");
currentInputDevice = InputDeviceType.Playstation;
}
else if (device is XInputController)
{
Debug.Log("Last used device is an Xbox Controller");
currentInputDevice = InputDeviceType.Xbox;
}
else
{
Debug.Log("Unknown Controller!");
}
break;
case Keyboard or Mouse:
Debug.Log("Last used device is Keyboard and mouse!");
currentInputDevice = InputDeviceType.PC;
break;
default:
Debug.Log("Unrecognised control scheme");
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment