Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt123miller/be4efce8389240eb9029189d1178374e to your computer and use it in GitHub Desktop.
Save matt123miller/be4efce8389240eb9029189d1178374e to your computer and use it in GitHub Desktop.
Debug meshes
using UnityEngine;
public class DebugDrawGameObjectMesh : MonoBehaviour
{
[Header("Configuration")]
[Space]
public bool drawWireMesh = true;
public Color wireColor = new Color(0, 0, 0, .8f);
[Space]
public bool drawFaceMesh = false;
public Color faceColor = new Color(0, .5f, 0, .2f);
[Space]
public bool drawVertexNormal = false;
public float vertexNormalSize = .05f;
public Color vertexNormalColor = Color.blue;
[Space]
public bool drawFaceNormal = false;
public float faceNormalSize = .05f;
public Color faceNormalColor = Color.yellow;
[Space]
public MeshFilter meshFilter;
void OnDrawGizmos()
{
if (meshFilter)
{
if (drawWireMesh)
{
GizmosDrawWireMesh();
}
if (drawFaceMesh)
{
GizmosDrawFaceMesh();
}
if (drawVertexNormal)
{
GizmosDrawVertexNormals();
}
if (drawFaceNormal)
{
GizmosDrawFaceNormals();
}
}
}
void GizmosDrawWireMesh()
{
Gizmos.color = wireColor;
Gizmos.matrix = Matrix4x4.identity;
Gizmos.DrawWireMesh(meshFilter.sharedMesh, transform.position, transform.rotation, transform.localScale);
}
void GizmosDrawFaceMesh()
{
Gizmos.color = faceColor;
Gizmos.matrix = Matrix4x4.identity;
Gizmos.DrawMesh(meshFilter.sharedMesh, transform.position, transform.rotation, transform.localScale);
}
void GizmosDrawVertexNormals()
{
Gizmos.color = vertexNormalColor;
Gizmos.matrix = transform.localToWorldMatrix;
// get data
Vector3[] vertices = meshFilter.sharedMesh.vertices;
Vector3[] normals = meshFilter.sharedMesh.normals;
// draw
for (int i = 0; i < normals.Length; i++)
{
Gizmos.DrawLine(vertices[i], vertices[i] + normals[i] * vertexNormalSize);
}
}
void GizmosDrawFaceNormals()
{
// precache data
int i1, i2, i3;
Vector3 p1, p2, p3, center, u, v, normal;
Gizmos.color = faceNormalColor;
Gizmos.matrix = transform.localToWorldMatrix;
Vector3[] vertices = meshFilter.sharedMesh.vertices;
int[] triangles = meshFilter.sharedMesh.triangles;
for (int i = 0; i < triangles.Length; i += 3)
{
// get data
i1 = triangles[i];
i2 = triangles[i + 1];
i3 = triangles[i + 2];
p1 = vertices[i1];
p2 = vertices[i2];
p3 = vertices[i3];
center = p1 / 3 + p2 / 3 + p3 / 3;
// calculate normals
u = p2 - p1;
v = p3 - p1;
normal = new Vector3();
normal.x = u.y * v.z - u.z * v.y;
normal.y = u.z * v.x - u.x * v.z;
normal.z = u.x * v.y - u.y * v.x;
// draw
Gizmos.DrawLine(center, center + normal.normalized * faceNormalSize);
}
}
void Reset()
{
meshFilter = GetComponent<MeshFilter>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment