Hello there,
I have an object having several materials applied to it (Element 0 to Element 3).
I do this:
if (!Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition), hit, 300))
return;
so I can get the whole material of the object clicked with this:
hit.transform.gameObject.renderer.materials[0].name
But is there a way I can get directly the material index I clicked ? (or any simple way to code it ?)
I looked in RaycastHit variables, but can’t find anything suited.
Thank you very much,
SMaX
The only thing I can think of is that you might be able to use the triangleIndex property of RaycastHit. If you know which ranges of triangles correspond to which materials, you could use this to find the material.
Here you go, hopefully it works.
using UnityEngine;
public class FindHitSubMesh : MonoBehaviour {
private int[] subMeshesFaceTotals;
private int totalSubMeshes;
void Awake()
{
MeshFilter mf = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter));
Mesh mesh = mf.mesh;
totalSubMeshes = mesh.subMeshCount;
subMeshesFaceTotals= new int[totalSubMeshes];
for(int i=0; i<totalSubMeshes; i++)
{
subMeshesFaceTotals[i] = mesh.GetTriangles(i).Length /3;
}
}
void OnMouseDown()
{
RaycastHit hit;
if (!Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, Mathf.Infinity))
return;
int hitSubMeshNumber = 0;
int maxVal= 0;
for(int i=0; i<totalSubMeshes; i++)
{
maxVal += subMeshesFaceTotals[i];
if (hit.triangleIndex <= maxVal-1 )
{
hitSubMeshNumber = i+1;
break;
}
}
Debug.Log("We hit sub mesh number: " + hitSubMeshNumber);
}
}
5 Likes
Thank you damien,
I got your script working, so i’ll try to figure out a way to have a single script in my scene handling all my objects in once.
Thanks again
SMaX
Man thank you so much, still helpful