Why is Unity3D RaycastHit.textureCoord always 0,0?

unity-game-engine

Solution

Actually let me move my comment here, does the sphere use a mesh collider or a sphere collider? If it doesn't use a mesh collider, textureCoord returns Vector2.zero.

Update:

To change the collider type of a GameObject highlight it in the Unity editor and go to Component->Physics->MeshCollider. If prompted to 'Replace Existing Component', select 'Replace'.

GameObjects added from Unity's GameObject->Create_Other menu tend to default to colliders based on the shape of the object (spheres, boxes, etc), since mesh colliders are computationally more expensive.

Problem

``` var startPoint = shaft.transform.position + shaft.transform.forward; var ray = new Ray( startPoint, -shaft.transform.forward ); RaycastHit rayCastHit; Physics.Raycast(ray, out rayCastHit); var textured2D = (Texture2D)discoBall.renderer.material.mainTexture; Vector2 textureCoord = rayCastHit.textureCoord; Debug.Log(string.Format( "{0},{1} at distance {2}", textureCoord.x * textured2D.width, textureCoord.y * textured2D.height, rayCastHit.distance )); ``` I have a sphere with an object "Shaft" object inside it. I work out a startPoint as a distance away from the shaft in the direction the shaft points (to get outside the sphere). I then create a ray pointing back at the sphere with the same distance, so that it collides with the outside of my sphere. The Debug.Log outputs x,y = 0,0 for the textureCoord, and the correct value of 0.35 for the distance. Why is the textureCoord always 0,0 when I do in fact have a material with a texture on my sphere?

Original source