Getting UV coordinate with GraphicRaycaster

Hey everyone,

I’m trying (and failing) to use the GraphicRaycaster to get the UV coordinate of an UI Image at my cursor position in a similar fashion as RaycastHit.textureCoord. I can’t seem to find anything resembling such information in RaycastResult.

I want to use the UV coordinates found by clicking on a render texture as input for ViewportPointToRay and I used to do this with a Physics.Raycast, however I’ve recently switched out that mesh with a UI element.

Anyone ever had a similar problem?

Thanks in advance

Same problem here… :frowning:

Hi @TurboHermit!

This is was posted long time ago, but this is a solution I’ve found using the RectTransformUtility:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Test : MonoBehaviour
{
    private GraphicRaycaster graphicRaycaster;
    private EventSystem eventSystem;
    private PointerEventData eventData;

    void Start() {
        //The GraphicRaycaster component in the Canvas
        graphicRaycaster = GetComponent<GraphicRaycaster>();
        //The EventSystem in the Scene
        eventSystem = GameObject.Find("EventSystem").GetComponent<EventSystem>();
    }
    
    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
            //Create a PointerEventData to pass in the Raycast
            eventData = new PointerEventData(eventSystem);
            eventData.position = Input.mousePosition;
            //Create a RaycasResult list to pass in the Raycast
            List<RaycastResult> results = new List<RaycastResult>();

            graphicRaycaster.Raycast(eventData, results);
            
            foreach (RaycastResult result in results)
            {
                //Check if you hitted the image
                if (result.gameObject.name == "your image name") {
                    Vector2 localPosition; //the local position in the image Rect coordinates
                    RectTransform rectTransform = result.gameObject.GetComponent<RectTransform>();
                    
                    //This obtains the position of the pointer in the image rect coordinates
                    RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, 
                    eventData.position, Camera.main, out localPosition);

                    Debug.Log(localPosition);
                }
            }

            
        }
    }
}