RaycastHit.textureCoord Always Zero

Using the sample screen to world raycast code to find the uv coordinates of a texture that the unity documents provide only ever give me 0,0. It use to work when I first tried and the textureCoord would be something other than 0,0. Now it won't work no matter what I try. So maybe I changed something that I am just over looking?

if (!Input.GetMouseButtonDown(0))
        return;

    RaycastHit hit;
    if (!sphere.collider.Raycast(camera.ScreenPointToRay(Input.mousePosition), out hit, 1000.0f))
        return;

    Renderer renderer = hit.collider.renderer;

    if (renderer == null || renderer.sharedMaterial == null ||
    renderer.sharedMaterial.mainTexture == null)
    {
        Debug.Log("Something not set");
        return;
    }

    // Now draw a pixel where we hit the object
    Texture2D tex = (Texture2D)renderer.material.mainTexture;
    Vector2 pixelUV = hit.textureCoord;
    Debug.Log("UV:"+pixelUV.ToString());
    pixelUV.x *= tex.width;
    pixelUV.y *= tex.height;
    Debug.Log("Cord:"+pixelUV.ToString());

While the english is bad and an edit should probably be submitted, the docs for RaycastHit.textureCoord say

If the collider is no mesh collider, zero Vector2 will be returned.

I think that means

If RaycastHit.collider is not a MeshCollider, Vector2.zero will be returned.

Which would explain that it might have worked if you had been previously using a mesh collider and would have stopped if your collider was no longer a mesh collider.

1 Like