- Home /
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());
Answer by skovacs1 · Oct 06, 2010 at 07:29 PM
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.
Not sure if this is what is meant, but just to clarify a Sphere Collider is not a $$anonymous$$esh Collider and will return (0,0). To fix simply replace the Sphere Collider with a $$anonymous$$esh Collider.