TrackerIndexManager.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Text;
  4. using UnityEngine;
  5. using Valve.VR;
  6. using Debug = UnityEngine.Debug;
  7. namespace Tracking
  8. {
  9. public class TrackerIndexManager : MonoBehaviour
  10. {
  11. private IEnumerable<IViveTracker> trackers;
  12. private void OnEnable()
  13. {
  14. SteamVR_Events.DeviceConnected.Listen(OnDeviceConnected);
  15. trackers = GetComponentsInChildren<IViveTracker>();
  16. }
  17. private void OnDeviceConnected(int index, bool connected)
  18. {
  19. if (index < 0) return;
  20. if (!connected || OpenVR.System == null) return;
  21. var deviceClass = OpenVR.System.GetTrackedDeviceClass((uint) index);
  22. if (deviceClass != ETrackedDeviceClass.GenericTracker) return;
  23. var error = ETrackedPropertyError.TrackedProp_Success;
  24. var serialNumberBuilder = new StringBuilder();
  25. OpenVR.System.GetStringTrackedDeviceProperty((uint) index,
  26. ETrackedDeviceProperty.Prop_SerialNumber_String, serialNumberBuilder, 64, ref error);
  27. if (error != ETrackedPropertyError.TrackedProp_Success)
  28. {
  29. Debug.LogError($"Could not get serial number for tracker at index {index}");
  30. }
  31. else
  32. {
  33. UpdateTrackerObject(serialNumberBuilder.ToString(), index);
  34. }
  35. }
  36. private void UpdateTrackerObject(string id, int index)
  37. {
  38. Debug.Log($"Tracker with serial number {id} got connected at index {index}");
  39. var t = trackers.FirstOrDefault(tracker => tracker.Id == id);
  40. t?.TrackedObject.SetDeviceIndex(index);
  41. }
  42. }
  43. }