Unity: Detect VR Mode

Create a new "VRGameController" script as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;

public class VRGameController : MonoBehaviour
{
    [SerializeField] GameObject[] disableComponenetsOnVR;

    // Start is called before the first frame update
    void Start()
    {
        if (IsXrDevicePresent()) {
            for (int i = 0; i < disableComponenetsOnVR.Length; i++) {
                GameObject go = (GameObject)disableComponenetsOnVR[i];
                go.SetActive(false);
            }
        }
    }

    bool IsXrDevicePresent()
    {
        List<XRDisplaySubsystem> xrDisplaySubsystems = new List<XRDisplaySubsystem>();
        SubsystemManager.GetInstances<XRDisplaySubsystem>(xrDisplaySubsystems);
        foreach (XRDisplaySubsystem xrDisplay in xrDisplaySubsystems)
        {
            if (xrDisplay.running)
            {
                return true;
            }
        }
        return false;
    }

    void Update()
    {
       
    }
}

Create an empty game object in the level and add the VRGameController script. You can then disable non-VR elements (such as a standard non-VR first-person camera or canvas) using the disable list. Note you can create an "enable list" in a similar fashion if needed.


Updated for Unity 2020.3.26f1 on 2022.01.18.

Comments

Popular Posts