Hi i want to paint texture of hitted enemy and i have everything except one thing.
i can’t get texture uvcoordinat of object because i am using box colliders on enemy (legs , arms , head …) so how can i get texcoordinate in this situation
Current stuck : when i hit collider im calculating the nearest mesh vertex to hit.point but still can’t get hitted point uvcordinat
You can’t really do that because a sphere collider representation doesn’t have uvs, it’s just a mathematical concept without underlying mesh.
If you want to get your exact uv coordinates
If you have a SkinnedMesh, you probably need to bake it into a new Mesh and use that, but I’m sure that there are libraries for that somewhere.
An example for a use case I had: I wanted to figure out the UVs of the visual sphere mesh that is on the sphere object (basically the mesh of the MeshFilter.sharedMesh of that object).
What I did for this is to set up a MeshCollider as child of the sphere collider, then assign the same Sphere Mesh to it as the one the MeshFilter of a Sphere object uses. It is important to set the mesh collider to non-convex (cooking option settings might not be required, but I disabled them) so that the visual mesh representation and the physical mesh representation is the same. Then I disabled that collider and stored a reference to it on a script on the original sphere parent object.
So when I hit the sphere, I check for that component, then get the MeshCollider from it and perform the same raycast, but only against this one collider, using Collider.Raycast (on the collider instance) instead of Physics.Raycast. Then I got the uv coordinates I was looking for. While testing, apparently collider.Raycast only gets me valid values when the collider is enabled, and the object it sits on is active.
Since I don’t want that collider to be part of my regular physics interactions, I only activate and enabled it just before I do the raycast, and then I disable it again.
Some people in other threads mention that sometimes it doesn’t work in builds. The reason is because some meshes might have isReadable not enabled, that means that after the mesh gets uploaded to the GPU-accessible memory, it gets cleared from the CPU-accessible memory - a sideeffect seems to be that the RaycastHit texture coordinates can’t retrieve valid values when this is the case. The solution is to set the “readable/writeable” flag on the import settings of the model/fbx that stores your mesh to true (mesh needs to have isReadable enabled)
If you don’t want to do that, you might have to create a compute shader and iterate all vertices of your (baked) visual mesh and store the vertexID that is the closest to your hit point, and then use the uv coordinate on that vertexID (index) as your value.