using UnityEngine; using TMPro; using System; /// /// MonoBehaviour wrapper for OpenVRNativeAccess that can be attached to GameObjects. /// This script uses the static OpenVRNativeAccess class to interact with the native plugin /// and displays the gyroscope data on a TextMeshProUGUI component. /// public class OpenVRNativeGyroscope : MonoBehaviour { [Header("References")] [Tooltip("TextMeshProUGUI component to display the gyroscope data")] public TextMeshProUGUI gyroText; [Header("Settings")] [Tooltip("How often to update the display (in seconds)")] public float updateInterval = 0.05f; // Private variables private bool pluginInitialized = false; private float timeSinceLastUpdate = 0f; private Vector3 lastGyroData = Vector3.zero; private bool lastTrackingValid = false; void Start() { Debug.Log("OpenVRNativeGyroscope: Start called"); if (gyroText == null) { Debug.LogError("TextMeshProUGUI reference not set"); return; } // Initialize the native plugin try { pluginInitialized = OpenVRNativeAccess.InitializePlugin(); if (pluginInitialized) { Debug.Log("Native plugin initialized successfully"); Debug.Log($"Driver name: {OpenVRNativeAccess.GetDriverNameString()}"); } else { Debug.LogError("Failed to initialize native plugin"); gyroText.text = "Failed to initialize plugin"; } } catch (Exception e) { Debug.LogError($"Error initializing native plugin: {e.Message}"); gyroText.text = $"Plugin error: {e.Message}"; pluginInitialized = false; } } void Update() { if (!pluginInitialized || gyroText == null) return; // Update at the specified interval timeSinceLastUpdate += Time.deltaTime; if (timeSinceLastUpdate < updateInterval) return; timeSinceLastUpdate = 0f; // Check if the headset is connected if (!OpenVRNativeAccess.IsHeadsetConnected()) { gyroText.text = "Headset not connected"; return; } // Get the raw gyroscope data float x, y, z; bool success = OpenVRNativeAccess.GetRawGyroscopeData(out x, out y, out z); if (success) { lastGyroData = new Vector3(x, y, z); } // Get tracking state bool trackingValid = OpenVRNativeAccess.IsTrackingValid(); lastTrackingValid = trackingValid; // Format and display the gyroscope data gyroText.text = string.Format("Native Gyro:\nX: {0:F2}\nY: {1:F2}\nZ: {2:F2}", lastGyroData.x, lastGyroData.y, lastGyroData.z); // Add tracking status // if (!trackingValid) // { // gyroText.text += "\n(Tracking lost)"; // } // Add magnitude gyroText.text += $"\nMag: {lastGyroData.magnitude:F2}"; } void OnDestroy() { // Shutdown the native plugin if (pluginInitialized) { try { OpenVRNativeAccess.ShutdownPlugin(); Debug.Log("Native plugin shut down"); } catch (Exception e) { Debug.LogError($"Error shutting down native plugin: {e.Message}"); } } } }