RaycastHit.textureCoord ranges from (0,0) to (1,1) for each face.

Hi all,

I have a simple cube, with a material applied. I am casting a ray at it from mouse click positions and looking at the value of textureCoord in the RaycastHit structure. No matter which side of my cube I click, texture coord always gets a value of (0, 0) if I click near the bottom left, and (1, 1) near the top right. It’s reporting the coordinate I clicked within the texture on that side of the cube, not the texture as a whole. Does anyone know why it’s doing this? Or how I can stop it? To clarify;

The texture on my cube is actually a RenderTexture being captured from a camera elsewhere in my scene. That camera’s preview looks like this;


And I have the UVs on my cube set up so that each one of those numbers in the texture maps nicely to one side of the cube like so;

Given the way my texture is set up I would expect that when I click near the corner I’ve marked “A”, I would find a texture Coord of roughly (0, 0.6), B would be (0.33, 1), C (0.33, 0) and D (0.66, 0.4). However what I actually get is A = (0, 0), B = (1, 1), C = (0, 0), D = (1, 1). And the same is true of all the other sides too.

Does anyone know what I am doing wrong?

Do you actually have a MeshCollider on your gameobject? The BoxCollider can not return any texture coordinates. Actually any of the primitive colliders (Box, Sphere, Capsule) will not return any texture coordinates. Only the MeshCollider can actually refer to the Mesh it uses

@Bunny83, you were completely right about making sure I was using the same mesh for rendering and colliding. I’m just posting the details as a separate answer so I can accept it, without making it look like the problem was just that I wasn’t using a MeshCollider at all, as per your first suggestion.

In my case I had started with the default cube object the editor creates for you. I replaced the default collider with a meshcollider and gave it a reference to the cube mesh that was there on the object by default. That would have worked all fine, however I also had my own script on the object which, among other things, modified the mesh’s UVs. It did that by calling;

GetComponent<MeshFilter>().mesh.uv = myCustomUVs

The problem being that the call to “.mesh” instantiates and returns a new copy of the mesh that the meshfilter uses from then on, but obviously my Mesh Collider was still using the original mesh with the default uvs. Simply adding the following, later in my script, fixed it.

GetComponent<MeshCollider>().sharedMesh = GetComponent<MeshFilter>().mesh

Thanks for the help!