Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Visualize mesh normals in Unity3D

Visualize the normals of a mesh

It's meant to be simple and easy to use, and therefore it has been made as a custom editor of MeshFilter. It needs no preparations.

How to use

Drop the file in an Editor folder.

using UnityEditor;
using UnityEngine;
public class NormalsVisualizer : Editor {
private Mesh mesh;
void OnEnable() {
MeshFilter mf = target as MeshFilter;
if (mf != null) {
mesh = mf.sharedMesh;
void OnSceneGUI() {
if (mesh == null) {
Handles.matrix = (target as MeshFilter).transform.localToWorldMatrix;
Handles.color = Color.yellow;
Vector3[] verts = mesh.vertices;
Vector3[] normals = mesh.normals;
int len = mesh.vertexCount;
for (int i = 0; i < len; i++) {
Handles.DrawLine(verts[i], verts[i] + normals[i]);

This comment has been minimized.

Copy link

@JocelynSachs JocelynSachs commented Feb 18, 2021

You've probably noticed this script creates massive slowdown on complex objects. This is for two reasons:

  1. You only need to set the Handles matrix and colour once.
  2. (much more serious): accessing mesh.vertices creates a copy of the entire vertex array. Same for accessing mesh.normals. Since you are accessing mesh.vertices twice and mesh.normals once for every vertex, you're forcing Unity to allocate and free up hundreds or thousands (or hundreds OF thousands) of vertex buffers every frame.

All you need to do is move the handles.matrix and colour lines outside the loop, and cache mesh.vertices and mesh.normals in local arrays, too:

Vector3 verts = mesh.vertices;
Vector3 norms = mesh.normals;

for (int.....)


This comment has been minimized.

Copy link
Owner Author

@mandarinx mandarinx commented Feb 18, 2021

Thanks for pointing out the performance issues! One of the things I work with is performance optimizations, so it was rather embarrassing seeing this script again. I fully agree with you, and will update the gist. Thanks!

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