- Home /
Getting material index from raycast
Hi!
First of all, I don't know if index is the correct word for this. If it isn't, please correct me! Now for the problem. I am working on a footstep system and I need to find the right material the raycast hits. My map is built by tiles using full meshes so floor, walls and roof are all connected. Thanks to this I can not use tags and if I do a simple "check for material, do that if that material equals that" because the materials are in an array. Unfortunately the wall material is in first place and the floor always' last. So for the the "check material" method to work I need to walk on walls. So how can I check what material I am getting when it is in an array?
This is my code so far.
if (Physics.Raycast(groundCheckTransform.position, -Vector3.up, out groundHit, 0.4f, movementSettings.walkableLayer))
{
Material[] hitMaterial = hit.transform.GetComponent<Renderer>().materials;
}
The code doesn't do much at all at this stage. It just gets the objects materials and puts it in a array.
Thanks in advance!
Answer by MUGIK · Nov 26, 2021 at 05:52 PM
This worked for me:
public static int GetSubMeshIndex(Mesh mesh, int triangleIndex)
{
if (mesh.isReadable == false)
{
Debug.LogError("You need to mark model's mesh as Read/Write Enabled in Import Settings.", mesh);
return 0;
}
int triangleCounter = 0;
for (int subMeshIndex = 0; subMeshIndex < mesh.subMeshCount; subMeshIndex++)
{
var indexCount = mesh.GetSubMesh(subMeshIndex).indexCount;
triangleCounter += indexCount / 3;
if (triangleIndex < triangleCounter)
{
return subMeshIndex;
}
}
Debug.LogError(
$"Failed to find triangle with index {triangleIndex} in mesh '{mesh.name}'. Total triangle count: {triangleCounter}",
mesh);
return 0;
}
Answer by Cherno · Apr 09, 2015 at 10:11 PM
Get triangle index of the raycast hit: RaycastHit.triangleIndex
Use Mesh.GetTriangles to iterate through all triangles until you find the right material (= submesh) index.
@Cherno I have been experimenting with this but I can't figure out how or what I am supposed to use sub$$anonymous$$eshCount and $$anonymous$$esh.GetTriangles for. Could you help me a bit with this?