It seems raycast hit does not work for UI... is it possible to get the .textureCoord of a point hit by the mouse on a UI raw image? (raw image provided by a render camera elsewhere far far away)


1 Answer 1


The RectTransformUtility has a helper method for finding the position of a screen point inside anyRectTransform's bounding rectangle:

var rt = (RectTransform)rawImage.transform;

bool inside = RectTransformUtility.ScreenPointToLocalPointInRectangle(
    out Vector2 pointInRect

Then you can just remap these coordinates from the local rectangle of the RawImage object into the UV space of the texture it's displaying:

if (inside) {
    Vector2 textureCoord = pointInRect - rt.rect.min;
    textureCoord.x *= rawImage.uvRect.width / rt.rect.width;
    textureCoord.y *= rawImage.uvRect.height / rt.rect.height;
    textureCoord += rawImage.uvRect.min;

Note that if your UI is in "Screen Space - Overlay mode", then the camera argument should be null.

If your texture coordinates are upside-down, you may need to set

trextureCoord.y = rt.rect.height - textureCoord.y;

before the scaling step.

  • \$\begingroup\$ Okay, this surely beats my GraphicCaster attempt - thank you!!! \$\endgroup\$
    – ina
    Commented Jan 10, 2022 at 2:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .