Skip to content

Instantly share code, notes, and snippets.

@aleverdes
Last active December 12, 2023 22:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aleverdes/b6f14c61ac661c3b7ce9b9bf4c78bbdb to your computer and use it in GitHub Desktop.
Save aleverdes/b6f14c61ac661c3b7ce9b9bf4c78bbdb to your computer and use it in GitHub Desktop.
Unity OpenXR InputDeviceManager
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;
public class InputDeviceManager : MonoBehaviour
{
private HashSet<string> _loadedControllerInputDevices;
public InputDevice LeftController;
public InputDevice RightController;
private void Awake()
{
DontDestroyOnLoad(this);
_loadedControllerInputDevices = new HashSet<string>();
InputDevices.deviceConnected += OnDeviceConnected;
InputDevices.deviceDisconnected += OnDeviceDisconnected;
TryInitializeDevices();
}
private void OnDestroy()
{
InputDevices.deviceConnected -= OnDeviceConnected;
InputDevices.deviceDisconnected -= OnDeviceDisconnected;
}
private void TryInitializeDevices()
{
var listDevices = new List<InputDevice>();
InputDevices.GetDevices(listDevices);
foreach (var inputDevice in listDevices)
{
OnDeviceConnected(inputDevice);
}
}
private void OnDeviceConnected(InputDevice inputDevice)
{
Debug.Log($"Connected {inputDevice.name}");
if (_loadedControllerInputDevices.Contains(GetUniqueName(inputDevice)))
{
return;
}
if (inputDevice.characteristics.HasFlag(InputDeviceCharacteristics.Controller))
{
InitController(inputDevice);
}
}
private void OnDeviceDisconnected(InputDevice inputDevice)
{
var uniqueName = GetUniqueName(inputDevice);
_loadedControllerInputDevices.Remove(uniqueName);
}
private void InitController(InputDevice inputDevice)
{
var isLeftController = inputDevice.characteristics.HasFlag(InputDeviceCharacteristics.Left);
if (isLeftController)
{
LeftController = inputDevice;
}
else
{
RightController = inputDevice;
}
_loadedControllerInputDevices.Add(GetUniqueName(inputDevice));
}
private static string GetUniqueName(InputDevice inputDevice)
{
return $"{inputDevice.name}_{inputDevice.characteristics}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment