Last active
February 5, 2024 02:23
-
-
Save Janooba/c387ccd26b4fcdbb8a36dd65142769b5 to your computer and use it in GitHub Desktop.
Extensions needed for CSGAutoColliderAddBuildProcessor.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} | |
} |
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
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)