RayAttachModifier.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using Unity.XR.CoreUtils;
  2. using UnityEngine;
  3. using UnityEngine.XR.Interaction.Toolkit;
  4. using UnityEngine.XR.Interaction.Toolkit.Interactables;
  5. using UnityEngine.XR.Interaction.Toolkit.Interactors;
  6. namespace Unity.VRTemplate
  7. {
  8. /// <summary>
  9. /// Add this to your interactable to make it snap to the source of the XR Ray Interactor
  10. /// instead of staying at a distance. Has a similar outcome as enabling Force Grab.
  11. /// </summary>
  12. public class RayAttachModifier : MonoBehaviour
  13. {
  14. IXRSelectInteractable m_SelectInteractable;
  15. protected void OnEnable()
  16. {
  17. m_SelectInteractable = GetComponent<IXRSelectInteractable>();
  18. if (m_SelectInteractable as Object == null)
  19. {
  20. Debug.LogError($"Ray Attach Modifier missing required Select Interactable on {name}", this);
  21. return;
  22. }
  23. m_SelectInteractable.selectEntered.AddListener(OnSelectEntered);
  24. }
  25. protected void OnDisable()
  26. {
  27. if (m_SelectInteractable as Object != null)
  28. m_SelectInteractable.selectEntered.RemoveListener(OnSelectEntered);
  29. }
  30. void OnSelectEntered(SelectEnterEventArgs args)
  31. {
  32. if (!(args.interactorObject is XRRayInteractor))
  33. return;
  34. var attachTransform = args.interactorObject.GetAttachTransform(m_SelectInteractable);
  35. var originalAttachPose = args.interactorObject.GetLocalAttachPoseOnSelect(m_SelectInteractable);
  36. attachTransform.SetLocalPose(originalAttachPose);
  37. }
  38. }
  39. }