简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM