Created
September 21, 2022 20:54
-
-
Save kurtdekker/7e1838c00e40a8dff8c1df648bf8eb93 to your computer and use it in GitHub Desktop.
Clones and flips a piece of geometry, optionally using another material
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
// @kurtdekker | |
// | |
// Place on a MeshFilter / MeshRenderer GameObject. | |
// | |
// This will: | |
// - duplicate the entire GameObject via Instantiate | |
// (and obviously its children; those are ignored!) | |
// - parent it to the same place the original was | |
// - clone the mesh | |
// - flip all triangles in the mesh | |
// - assign the mesh back to the MeshFilter | |
// - optionally set the given new material in the Renderer | |
[RequireComponent( typeof( MeshFilter))] | |
public class CloneAndFlipTriangles : MonoBehaviour | |
{ | |
[Header( "Leave blank to use original materials.")] | |
public Material ReplacementMaterial; | |
void Awake() | |
{ | |
GameObject original = gameObject; | |
Transform parent = transform.parent; | |
// keep us from going indefinitely! | |
DestroyImmediate(this); | |
GameObject copy = Instantiate<GameObject>(original, parent); | |
MeshFilter mf = copy.GetComponent<MeshFilter>(); | |
Mesh mesh = Instantiate<Mesh>(mf.mesh); | |
int[] originalTriangles = mesh.triangles; | |
int triCount = originalTriangles.Length; | |
int[] tris = new int[ triCount]; | |
for (int i = 0; i < triCount; i += 3) | |
{ | |
// wind the triangles flipped the opposite way | |
tris[i + 0] = originalTriangles[i + 0]; | |
tris[i + 1] = originalTriangles[i + 2]; | |
tris[i + 2] = originalTriangles[i + 1]; | |
} | |
mesh.triangles = tris; | |
mesh.RecalculateNormals (); | |
mf.mesh = mesh; | |
if (ReplacementMaterial) | |
{ | |
Renderer mr = copy.GetComponent<Renderer>(); | |
mr.material = ReplacementMaterial; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment