This Unity script demonstrates how to track and display the position of an XR input device (such as a VR controller) using Unity's XR Input APIs. The script continuously updates and displays the position values of the specified device on the screen via a UI Text element.
- XR Device Tracking: Continuously obtains the XR device’s current positional data.
- Real-time UI Display: Displays device position updates in real-time on the UI.
- Efficient Input Handling: Only updates the display text when the device position changes significantly.
- Unity Engine (Tested with Unity 2021 or newer)
- XR Plugin Management configured (e.g., Oculus, OpenXR)
- UI Canvas set up with a
Text
UI element
- Clone the Repository
git clone https://github.com/david-neun/virtual-reality.git
- Setup the Unity Scene
- Ensure XR support is enabled in your Unity project settings (
Project Settings -> XR Plug-in Management
). - Create a Canvas and add a Text UI component.
Hierarchy Example:Canvas └── Text (Rename to 'ValoresText' or similar)
- Attach the Script
- Attach the provided
Track.cs
script to an empty GameObject. - Assign the created UI Text component (
valores
) from your Canvas to thevalores
field in the script through the Unity inspector.
- Run your scene in Play mode with an XR device connected (e.g., Oculus controller).
- The UI Text element will display real-time positional values of the XR device.
(0.123, 1.456, -0.789)
Values represent the XR device’s coordinates in Unity's virtual space (X, Y, Z), formatted to 3 decimal places.
Method | Description |
---|---|
GetDevice() |
Retrieves and assigns the XR device to track (left-hand controller in this script). |
OnEnable() |
Checks device validity and retrieves device information on script initialization. |
Update() |
Continuously fetches the device’s position and updates the UI when changes are detected. |
├── Assets
│ ├── Scripts
│ │ └── Track.cs
│ └── Scenes
│ └── SampleScene.unity
├── Packages
├── ProjectSettings
└── README.md
- UnityEngine.XR
- UnityEngine.UI
This project is available under the MIT License. See LICENSE
file for details.