Skip to content

Instantly share code, notes, and snippets.

@efagerberg
Last active December 16, 2021 23:11
Show Gist options
  • Save efagerberg/9ffe57a13bb9fce6cec5f46951c13040 to your computer and use it in GitHub Desktop.
Save efagerberg/9ffe57a13bb9fce6cec5f46951c13040 to your computer and use it in GitHub Desktop.
Unity script to turn on/off HMD simulator if a headset is connected/disconnected
public class HeadsetDetector : MonoBehaviour
{
private InputDeviceCharacteristics headsetCharacteristic = InputDeviceCharacteristics.HeadMounted;
private XRDeviceSimulator simulator;
private void Awake()
{
simulator = GetComponent<XRDeviceSimulator>();
simulator.enabled = true;
}
private void OnEnable()
{
InputDevices.deviceConnected += TurnOffSimulatorIfHMD;
InputDevices.deviceDisconnected += TurnOnSimulatorIfHMD;
}
private void OnDisable()
{
InputDevices.deviceConnected -= TurnOffSimulatorIfHMD;
InputDevices.deviceDisconnected -= TurnOnSimulatorIfHMD;
}
private void TurnOffSimulatorIfHMD(InputDevice device)
{
if (!device.characteristics.HasFlag(headsetCharacteristic))
return;
simulator.enabled = false;
}
private void TurnOnSimulatorIfHMD(InputDevice device)
{
if (!device.characteristics.HasFlag(headsetCharacteristic))
return;
simulator.enabled = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment