Last active
December 12, 2023 22:15
-
-
Save aleverdes/b6f14c61ac661c3b7ce9b9bf4c78bbdb to your computer and use it in GitHub Desktop.
Unity OpenXR InputDeviceManager
This file contains 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 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