Skip to content

Instantly share code, notes, and snippets.

@Janooba
Last active February 5, 2024 02:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Janooba/c387ccd26b4fcdbb8a36dd65142769b5 to your computer and use it in GitHub Desktop.
Save Janooba/c387ccd26b4fcdbb8a36dd65142769b5 to your computer and use it in GitHub Desktop.
Extensions needed for CSGAutoColliderAddBuildProcessor.cs
public static class UnityExtensions
{
public static Transform FindDeepChild(this Transform aParent, string aName)
{
Queue<Transform> queue = new Queue<Transform>();
queue.Enqueue(aParent);
while (queue.Count > 0)
{
var c = queue.Dequeue();
if (c.name == aName) return c;
foreach (Transform t in c) queue.Enqueue(t);
}
return null;
}
public static Material GetMaterial(this RaycastHit hit)
{
MeshCollider collider = hit.collider as MeshCollider;
if (!collider)
return null;
Mesh mesh = collider.sharedMesh;
// Finds the submesh that contains the hit triangle
int submesh;
for (submesh = 0; submesh < mesh.subMeshCount; submesh++)
{
var submeshInfo = mesh.GetSubMesh(submesh);
if (
hit.triangleIndex >= submeshInfo.indexStart
&& hit.triangleIndex < submeshInfo.indexStart + submeshInfo.indexCount
)
break;
}
MeshRenderer renderer = collider.GetComponent<MeshRenderer>();
if (!renderer)
renderer = collider.GetComponentInParent<MeshRenderer>();
if (!renderer)
return null;
return renderer.sharedMaterials[submesh];
}
}
@grenappels
Copy link

hello, thanks for writing this! i noticed the call to mesh.GetTriangles(submesh) adds 4kb of garbage in profiling, so i optimized the logic a bit and it got down to just 40b (seems like accessing sharedMaterials at all does that)

        // Finds the submesh that contains the hit triangle
        int submesh;
        for (submesh = 0; submesh < mesh.subMeshCount; submesh++)
        {
            var submeshInfo = mesh.GetSubMesh(submesh);
            if (
                hit.triangleIndex >= submeshInfo.indexStart
                && hit.triangleIndex < submeshInfo.indexStart + submeshInfo.indexCount
            )
                break;
        }

@Janooba
Copy link
Author

Janooba commented Feb 5, 2024

Nice find! I'll swap it out for future peeps 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment