Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Last active September 22, 2022 10:53
Show Gist options
  • Save kurtdekker/28ddd4671839184d31273f78bd7559a0 to your computer and use it in GitHub Desktop.
Save kurtdekker/28ddd4671839184d31273f78bd7559a0 to your computer and use it in GitHub Desktop.
Makes geometry double-sided by re-winding copies of each triangle to face the other way
using UnityEngine;
// @kurtdekker - quick double-siding mechanism.
//
// Place or add this Component to things with at
// least a MeshFilter on them.
//
// Presently only for single-submesh geometry.
[RequireComponent( typeof( MeshFilter))]
public class MakeGeometryDoubleSided : MonoBehaviour
{
void Awake()
{
MeshFilter mf = GetComponent<MeshFilter>();
// If this blows up you failed to meet the documented
// requirement above that a MeshFilter be present.
int vertCount = mf.mesh.vertices.Length;
// we need to dupe all verts so we can have lighting / UV info
Vector3[] verts = new Vector3[ vertCount * 2];
for (int i = 0; i < vertCount; i++)
{
verts [i] = mf.mesh.vertices [i];
verts [i + vertCount] = mf.mesh.vertices [i];
}
// and of course dupe all triangles
int triCount = mf.mesh.triangles.Length;
int[] tris = new int[ triCount * 2];
for (int i = 0; i < triCount; i += 3)
{
// re-add the original triangles, no change
tris[i + 0] = mf.mesh.triangles[i + 0];
tris[i + 1] = mf.mesh.triangles[i + 1];
tris[i + 2] = mf.mesh.triangles[i + 2];
// now add triangles flipped the opposite way
tris[i + triCount + 0] = mf.mesh.triangles[i + 0] + vertCount;
tris[i + triCount + 1] = mf.mesh.triangles[i + 2] + vertCount;
tris[i + triCount + 2] = mf.mesh.triangles[i + 1] + vertCount;
}
mf.mesh.vertices = verts;
mf.mesh.triangles = tris;
mf.mesh.RecalculateNormals ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment