I am working with XR Interaction Toolkit 2.2.0 and Unity 2022.2.7f1 and I have a Complete XR Origin Set Up Prefab in my Scene with some UI elements to click on (buttons with Tracked Device Ray Caster Script). I have a XR Device Simulator to move the controllers and the camera and everything works fine, the cursor turns blue when I hover a button and the button also changes color.
I need to get some properties from the hovered UI elements to make some changes on the controller appearence. Thus, it would be nice to have a script attached to the controller that can access the UI element currently being hovered.
I made a test script that I attached to the Ray Interactor to see if I could do it in a simple way :
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.XR.Interaction.Toolkit;
[RequireComponent(typeof(XRRayInteractor))]
public class AccessCurrentlyHoveredElement : MonoBehaviour
{
private XRRayInteractor rayInteractor = null;
void Start(){
rayInteractor = GetComponent<XRRayInteractor>();
rayInteractor.hoverEntered.AddListener(Test);
}
private void Test(HoverEnterEventArgs arg0)
{
Debug.Log("Hover Enter Triggered");
}
void Update(){
if(rayInteractor.IsOverUIGameObject()){
Debug.Log(rayInteractor.interactablesHovered.Count);
Debug.Log(rayInteractor.GetOldestInteractableHovered());
}
}
}
My problem is that when I test it, the IsOverUIGameObject method works fine but the hoverEntered event is never triggered, the interactablesHovered is always empty and the GetOldestInteractableHovered always returns null . So I know when a UI element is being hovered but I cannot access it.
Is there a way to do it ?
So, one solution could be to attach an event trigger to each UI element that you want to track? That way you can call a custom function in your AccessCurrentlyHoveredElement script whenever the hover event is triggered.
You'd have to do this for each UI element:
Now, whenever the pointer enters the UI button, the Test function in your AccessCurrentlyHoveredElement script will be called, and you can access the currently hovered UI element from there.
To get info/ data from the UI element, you should be able to get everything you need using the eventData parameter of the event trigger method. So, you'd need to modify the Test method like so: