'how to get a specific material from a meshrenderer using raycasts

I have a Meshrenderer with 9 materials on it and I want to detect which one of those colors is facing forward, but I don't know which one it is going to be so I can't just use Meshrenderer.materials[number].color

here is what I have so far

    public GameObject Shot1pos;

            RaycastHit hit;
            if (Physics.Raycast(Shot1pos.transform.position, Shot1pos.transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity))
            {
                Debug.DrawRay(Shot1pos.transform.position, Shot1pos.transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
                Wheel1Color = hit.collider.gameObject.GetComponent<MeshRenderer>().material.color;
                Debug.Log(Wheel1Color);
            }

but this only returns the first material, whichever is facing forward



Solution 1:[1]

I found the solution. First of all you need to get the mesh index according to hit.triangleIndex and get the main material index based on it.

For first one just copy this script in class:

public static int GetSubMeshIndex(Mesh mesh, int triangleIndex)
{
    if (!mesh.isReadable) return 0;
    
    var triangleCounter = 0;
    for (var subMeshIndex = 0; subMeshIndex < mesh.subMeshCount; subMeshIndex++)
    {
        var indexCount = mesh.GetSubMesh(subMeshIndex).indexCount;
        triangleCounter += indexCount / 3;
        if (triangleIndex < triangleCounter) return subMeshIndex;
    }
    
    return 0;
}

Then use this part for detecting Suitable material:

public void DetectMaterial(RaycastHit hit)
{
    if (hit.transform == null) return;

    var materials = hit.transform.GetComponent<MeshRenderer>().materials;

    var index = hit.triangleIndex;

    var mesh = hit.transform.GetComponent<MeshFilter>().mesh;
    
    var subMeshIndex = GetSubMeshIndex(mesh, index);
    
    UnityEngine.Debug.Log(materials[subMeshIndex]);
}

Remember that your file model must have Read / Write Enabled option enabled and use only Mesh Collider.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KiynL