Search code examples
c#unity-game-engineuser-interfacevirtual-realityraycasting

How do I raycast from a sphere to an ui element in the canvas


I would like to Raycast from the center of Sphere GameObject to find the text/image element being hit by the ray. I'm using Physics.RaycastAll to detect the UI element being hit. Following is my code.

public class RaycastUI : MonoBehaviour
{

    public GameObject Sphere;

    private Vector3 _origin;
    private Vector3 _direction;

    void Update()
    {
        RaycastHit[] hits;

        // get the origin and direction
        _origin = Sphere.transform.position;
        _direction = Sphere.transform.forward;

        //raycast all
        hits = Physics.RaycastAll(_origin, _direction, 100.0F);

        // retrieve the names of the element that are hit by the sphere.
        for (int i = 0; i < hits.Length; i++) {
            RaycastHit hit  = hits[i];
            Debug.Log(hit.collider.name);
        }
    }
}

I have added BoxCoilloider to the canvas. Unfortunately, hits.Length always returns 0. am I missing something? How do I ray cast from the sphere to the ui element in the canvas to check if it has collided?


Solution

  • I think you have to use the EventSystem if you want to check against UI elements.

    Try something like this:

    private void GetUIObjectsOfPosition(Vector2 screenPosition)
    {
        var eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = screenPosition;
    
        var results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
    
        foreach (var result in results) {
            Debug.Log(result.gameObject.name);
        }               
    }
    

    You can calculate the screen position from your spheres world position using Camera.WorldToScreenPoint.