Skip to content

Instantly share code, notes, and snippets.

@benui-dev
Created January 24, 2015 19:50
Show Gist options
  • Save benui-dev/5d59a26928a8ede8e3f1 to your computer and use it in GitHub Desktop.
Save benui-dev/5d59a26928a8ede8e3f1 to your computer and use it in GitHub Desktop.
Take a flat 2d poly mesh and return a mesh with MeshTopology.Lines of the outline. Good for text!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Outliner : BaseBehaviour
{
void Awake()
{
GetComponent<MeshFilter>().mesh
= FindOutlinePairs(GetComponent<MeshFilter>().mesh);
}
Mesh FindOutlinePairs(Mesh mesh)
{
var edges = new Dictionary<KeyValuePair<int, int>, int>();
for (int i = 0; i < mesh.triangles.Length; i += 3)
{
int idx1 = mesh.triangles[i];
int idx2 = mesh.triangles[i+1];
int idx3 = mesh.triangles[i+2];
KeyValuePair<int,int> a;
KeyValuePair<int,int> b;
KeyValuePair<int,int> c;
if (idx1 < idx2)
a = new KeyValuePair<int,int>(idx1, idx2);
else
a = new KeyValuePair<int,int>(idx2, idx1);
if (idx2 < idx3)
b = new KeyValuePair<int,int>(idx2, idx3);
else
b = new KeyValuePair<int,int>(idx3, idx2);
if (idx3 < idx1)
c = new KeyValuePair<int,int>(idx3, idx1);
else
c = new KeyValuePair<int,int>(idx1, idx3);
if (!edges.ContainsKey(a)) edges[a] = 0;
if (mesh.colors[idx1] == Color.white && mesh.colors[idx2] == Color.white)
edges[a] += 1;
if (!edges.ContainsKey(b)) edges[b] = 0;
if (mesh.colors[idx2] == Color.white && mesh.colors[idx3] == Color.white)
edges[b] += 1;
if (!edges.ContainsKey(c)) edges[c] = 0;
if (mesh.colors[idx3] == Color.white && mesh.colors[idx1] == Color.white)
edges[c] += 1;
}
var indices = new List<int>();
// Find all the edges with only 1 or two edges
foreach (var pair in edges)
{
if (pair.Value == 1)
{
indices.Add(pair.Key.Key);
indices.Add(pair.Key.Value);
}
}
var newMesh = new Mesh();
newMesh.vertices = mesh.vertices;
newMesh.SetIndices(indices.ToArray(), MeshTopology.Lines, 0);
return newMesh;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment