- Home /
Why in Unity3D RaycastHit. textureCoord always return 0,0 after building the project?
I need to get the pixel color from the texture when the Raycast beam collides with the object. Everything works fine in the unity editor, the coordinates of the beam collision and the pixel color are determined. After building the application, RaycastHit. textureCoord always returns the coordinates (0,0), respectively, the pixel color is also not correct. Has anyone ever encountered such a problem? And how can it be solved?
Texture2D tex = (Texture2D)Calc_Data.hit_center.collider.gameObject.GetComponent().material.mainTexture; // Get texture of object color_pixcel = tex.GetPixelBilinear(Calc_Data.hit_center.textureCoord.x, Calc_Data.hit_center.textureCoord.y); // Get color from texture
Answer by FM-Productions · Mar 31 at 01:34 PM
There are similar threads about this. It seems like for a RaycastHit to return valid coordinate values, the mesh has to be set to "readable". To be able to get correct coordinates, this means that the Mesh has to available on the GPU but also on the CPU - which comes with memory overhead. Sometimes this is the case in the Editor but not in builds, there might be an import setting on the model that has the data of the mesh that you can adjust. When this is not the case, the docs say that the mesh will be removed from CPU-addressable memory after it was uploaded to the GPU-addressable memory: I also found that you can't just check convex, because Unity will then prepare a different mesh for the collision calculations. This mesh won't return any valid textureCoord either when hit, at the very least it will misalign with the visual mesh you deal with. so the MeshCollider.sharedMesh property is not always the one that is actually being used by the physics engine. For the same reason (I haven't tested this though) I also just disabled cooking settings for meshes where I need to have correct textureCoords for Raycasts - to prevent the engine from preparing a different mesh representation for collision checks.
Relevant: - Turning on "Read/Write Enable" ptions on the target fbx might fix it: https://forum.unity.com/threads/raycasthit-texturecoord-always-0-0-in-standalone-if-fbx-model-read-write-not-enable.1108967/ - Further reading for Mesh.isReadable: https://docs.unity3d.com/ScriptReference/Mesh-isReadable.html