Skip to content

Instantly share code, notes, and snippets.

@jaburns
Last active January 23, 2018 18:04
Show Gist options
  • Save jaburns/32c6a0c8d718049dd8ee0cfdd60843af to your computer and use it in GitHub Desktop.
Save jaburns/32c6a0c8d718049dd8ee0cfdd60843af to your computer and use it in GitHub Desktop.
Create a copy of a mesh where each triangle has vertices with normals outward from the triangle
using UnityEngine;
using UnityEditor;
static public class FlattenMeshNormalsMenu
{
[MenuItem("GameObject/Flatten Mesh Normals", true)]
static bool GameObject_FlattenMeshNormals_validate()
{
var go = Selection.activeObject as GameObject;
if (go == null) return false;
return go.GetComponent<MeshFilter>() != null;
}
[MenuItem("GameObject/Flatten Mesh Normals", false, 10)]
static void GameObject_FlattenMeshNormals()
{
var mf = (Selection.activeObject as GameObject).GetComponent<MeshFilter>();
mf.sharedMesh = flattenNormals(mf.sharedMesh);
}
static Mesh flattenNormals(Mesh mesh)
{
var verts = new Vector3[mesh.triangles.Length];
var tris = new int[mesh.triangles.Length];
for (int i = 0; i < mesh.triangles.Length; ++i) {
verts[i] = mesh.vertices[mesh.triangles[i]];
tris[i] = i;
}
var ret = new Mesh();
ret.vertices = verts;
ret.triangles = tris;
ret.RecalculateNormals();
ret.RecalculateTangents();
ret.RecalculateBounds();
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment