109 lines
2.7 KiB
C#
109 lines
2.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace BitStrap
|
|
{
|
|
public class MirrorTool : MonoBehaviour
|
|
{
|
|
public Vector3 reflectNormal = Vector3.left;
|
|
|
|
[Header("Select things to be mirrored")]
|
|
public List<Transform> sourceRoots;
|
|
|
|
[ReadOnly]
|
|
[Header("Do NOT modify this")]
|
|
public List<Transform> destinationRoots;
|
|
|
|
[Button]
|
|
public void CreateMirror()
|
|
{
|
|
if (Application.isPlaying)
|
|
{
|
|
return;
|
|
}
|
|
DestroyMirror();
|
|
foreach (Transform sourceRoot in sourceRoots)
|
|
{
|
|
destinationRoots.Add(MirrorRoot(sourceRoot));
|
|
}
|
|
}
|
|
|
|
[Button]
|
|
public void DestroyMirror()
|
|
{
|
|
if (Application.isPlaying)
|
|
{
|
|
return;
|
|
}
|
|
foreach (Transform destinationRoot in destinationRoots)
|
|
{
|
|
if (destinationRoot != null)
|
|
{
|
|
UnityEngine.Object.DestroyImmediate(destinationRoot.gameObject);
|
|
}
|
|
}
|
|
destinationRoots.Clear();
|
|
}
|
|
|
|
private Transform MirrorRoot(Transform root)
|
|
{
|
|
Transform transform = UnityEngine.Object.Instantiate(root.gameObject).transform;
|
|
transform.name = root.name + "_Mirrored";
|
|
transform.parent = root.parent;
|
|
Transform[] componentsInChildren = transform.GetComponentsInChildren<Transform>(true);
|
|
foreach (Transform transform2 in componentsInChildren)
|
|
{
|
|
transform2.localPosition = Vector3.Reflect(transform2.localPosition, reflectNormal);
|
|
}
|
|
MeshFilter[] componentsInChildren2 = transform.GetComponentsInChildren<MeshFilter>(true);
|
|
foreach (MeshFilter meshFilter in componentsInChildren2)
|
|
{
|
|
meshFilter.sharedMesh = MirrorMesh(meshFilter.sharedMesh);
|
|
}
|
|
MeshCollider[] componentsInChildren3 = transform.GetComponentsInChildren<MeshCollider>(true);
|
|
foreach (MeshCollider meshCollider in componentsInChildren3)
|
|
{
|
|
meshCollider.sharedMesh = MirrorMesh(meshCollider.sharedMesh);
|
|
}
|
|
return transform.transform;
|
|
}
|
|
|
|
private Mesh MirrorMesh(Mesh srcMesh)
|
|
{
|
|
if (srcMesh == null)
|
|
{
|
|
return null;
|
|
}
|
|
Mesh mesh = new Mesh();
|
|
mesh.vertices = MirrorArray(srcMesh.vertices);
|
|
mesh.triangles = MirrorTriangles(srcMesh.triangles);
|
|
mesh.uv = srcMesh.uv;
|
|
mesh.uv2 = srcMesh.uv2;
|
|
mesh.normals = MirrorArray(srcMesh.normals);
|
|
mesh.colors = srcMesh.colors;
|
|
mesh.tangents = srcMesh.tangents;
|
|
mesh.UploadMeshData(true);
|
|
return mesh;
|
|
}
|
|
|
|
private Vector3[] MirrorArray(Vector3[] srcArray)
|
|
{
|
|
Vector3[] array = new Vector3[srcArray.Length];
|
|
for (int i = 0; i < srcArray.Length; i++)
|
|
{
|
|
array[i] = Vector3.Reflect(srcArray[i], reflectNormal);
|
|
}
|
|
return array;
|
|
}
|
|
|
|
private int[] MirrorTriangles(int[] srcTriangles)
|
|
{
|
|
int[] array = new int[srcTriangles.Length];
|
|
Array.Copy(srcTriangles, array, srcTriangles.Length);
|
|
Array.Reverse(array);
|
|
return array;
|
|
}
|
|
}
|
|
}
|