Skip to content

Instantly share code, notes, and snippets.

@russellweed
Created January 3, 2019 06:07
Show Gist options
  • Save russellweed/97dd833f67c58bbec683e4af5a31254b to your computer and use it in GitHub Desktop.
Save russellweed/97dd833f67c58bbec683e4af5a31254b to your computer and use it in GitHub Desktop.
Very rudimentary Unity VR SDK HMD Event notification junk
// DISCLAIMER: This was written late at night and is probably garbage.
// LICENSE: Do whatever you want with it. No attribution needed, but don't blame me if it doesn't work.
using UnityEngine;
using UnityEngine.XR;
public class VRManager : MonoBehaviour
{
public delegate void VRManagerEventHandler();
public static event VRManagerEventHandler LostFocus;
public static event VRManagerEventHandler ResumedFocus;
private bool hadFocus = true;
private VRSDK sdk = VRSDK.None;
protected virtual void OnLostFocus()
{
Debug.Log("VR DEVICE LOST FOCUS!");
if (LostFocus != null)
LostFocus();
}
protected virtual void OnResumedFocus()
{
Debug.Log("VR DEVICE RESUMED FOCUS!");
if (ResumedFocus != null)
ResumedFocus();
}
private void Awake()
{
// If we aren't using VR, turn all this off. It isn't needed
if (!XRSettings.enabled)
gameObject.SetActive(false);
hadFocus = true;
sdk = VRSDK.None;
if (XRSettings.loadedDeviceName == "Oculus")
sdk = VRSDK.Oculus;
else if (XRSettings.loadedDeviceName == "OpenVR")
sdk = VRSDK.SteamVR;
}
private void LateUpdate()
{
if (hadFocus)
{
// For Oculus HMDs, we need to detect headset removals or menu presses, and fire accordingly
if (sdk == VRSDK.Oculus)
{
if (!OVRManager.hasInputFocus || !OVRManager.hasVrFocus || XRDevice.userPresence == UserPresenceState.NotPresent)
hadFocus = false;
}
else // if (sdk == VRSDK.SteamVR) I don't know if there are SteamVR equivilents, so just stick w/ the generic Unity one?
{
if (XRDevice.userPresence == UserPresenceState.NotPresent)
hadFocus = false;
}
// If we just lost focus this frame, send a message
if (!hadFocus)
OnLostFocus();
}
else
{
// For Oculus HMDs, we need to detect headset removals or menu presses, and fire accordingly
if (sdk == VRSDK.Oculus)
{
if (OVRManager.hasInputFocus && OVRManager.hasVrFocus && XRDevice.userPresence != UserPresenceState.NotPresent)
hadFocus = true;
}
else // if (sdk == VRSDK.SteamVR) I don't know if there are SteamVR equivilents, so just stick w/ the generic Unity one?
{
if (XRDevice.userPresence != UserPresenceState.NotPresent)
hadFocus = true;
}
// If we just lost focus this frame, send a message
if (hadFocus)
OnResumedFocus();
}
}
public VRSDK GetSDK()
{
return sdk;
}
}
// WMR is using SteamVR so I don't care about anything else for now
public enum VRSDK
{
None,
Oculus,
SteamVR
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment