HandSubsystemManager.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.XR.Hands;
  4. namespace Unity.VRTemplate
  5. {
  6. /// <summary>
  7. /// This class is a convenience wrapper to handle external start/stop
  8. /// of a currently running XR Hand Subsystem.
  9. /// </summary>
  10. /// <seealso cref="XRHandSubsystem"/>
  11. public class HandSubsystemManager : MonoBehaviour
  12. {
  13. static List<XRHandSubsystem> s_HandSubsystems;
  14. XRHandSubsystem m_HandSubsystem;
  15. void OnEnable()
  16. {
  17. if (m_HandSubsystem == null)
  18. {
  19. TryGetHandSubsystem(out m_HandSubsystem);
  20. }
  21. }
  22. /// <summary>
  23. /// This function will attempt to find a currently running hand tracking subsystem and stop it.
  24. /// </summary>
  25. /// <seealso cref="XRHandSubsystem"/>
  26. public void DisableHandTracking()
  27. {
  28. if (m_HandSubsystem != null || TryGetHandSubsystem(out m_HandSubsystem))
  29. {
  30. m_HandSubsystem.Stop();
  31. }
  32. }
  33. /// <summary>
  34. /// This function will attempt to find a current hand tracking subsystem and start it up.
  35. /// </summary>
  36. /// <seealso cref="XRHandSubsystem"/>
  37. public void EnableHandTracking()
  38. {
  39. if (m_HandSubsystem != null || TryGetHandSubsystem(out m_HandSubsystem))
  40. {
  41. m_HandSubsystem.Start();
  42. }
  43. }
  44. // This is taken from XRInputTrackingAggregator and should be removed once the internal version
  45. // has been made publicly available.
  46. static bool TryGetHandSubsystem(out XRHandSubsystem handSubsystem)
  47. {
  48. s_HandSubsystems ??= new List<XRHandSubsystem>();
  49. SubsystemManager.GetSubsystems(s_HandSubsystems);
  50. if (s_HandSubsystems.Count == 0)
  51. {
  52. handSubsystem = default;
  53. return false;
  54. }
  55. if (s_HandSubsystems.Count > 1)
  56. {
  57. for (var i = 0; i < s_HandSubsystems.Count; ++i)
  58. {
  59. handSubsystem = s_HandSubsystems[i];
  60. if (handSubsystem.running)
  61. return true;
  62. }
  63. }
  64. handSubsystem = s_HandSubsystems[0];
  65. return true;
  66. }
  67. }
  68. }