Return Specific Material from RayCast

Longtime listener, first time caller.

I have a 3d scene where I am casting a ray from the camera toward a 3d object that contains multiple materials (one per side). I want to return the material of the side that the ray hits.

My current script (below) returns the same material (“material.002”) regardless of where I click or if I rotate the gameObject to show a different material/side:

Ray ray1 = cam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit1;
if (Physics.Raycast(ray1, out hit1))
{
Material obj1Color = hit1.transform.gameObject.GetComponent().material;
Debug.Log(obj1Color);
}

Any help is appreciated.

The issue is that the material field always returns the first material in the list.

Finding the correct material is complex, and there are a lot of ways you could go about this.

You could loop each submesh, and find the submeshes who’s bounding boxes have the hit point inside of them.

After that, if there are multiple bounding boxes found, then you’d need to do some wonky vertex checking stuff. Or maybe unity has a way to do a mesh collision check?