Last active
October 3, 2020 17:29
-
-
Save Anthelmed/366b2a3a4d525a7e5580c80ba535c516 to your computer and use it in GitHub Desktop.
Unity - Find and replace meshes that are identical but use different assets
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 System.Collections.Generic; | |
using System.Linq; | |
using UnityEditor; | |
using UnityEngine; | |
namespace AnthelmeDumontTools | |
{ | |
public class ReplaceDuplicateMeshesEditorWindow : EditorWindow | |
{ | |
private GameObject[] _selectedObjects; | |
private Vector2 _scrollPosition; | |
private GUIStyle _errorStyle = new GUIStyle(); | |
private void Awake() | |
{ | |
_errorStyle = new GUIStyle(); | |
_errorStyle.normal.textColor = Color.red; | |
} | |
[MenuItem("Tools/Replace Duplicate Meshes", false)] | |
private static void Init() | |
{ | |
var window = GetWindow<ReplaceDuplicateMeshesEditorWindow>("Replace Duplicate Mesh"); | |
window.Show(); | |
} | |
private void OnInspectorUpdate() | |
{ | |
Repaint(); | |
} | |
private void OnGUI() | |
{ | |
EditorGUILayout.LabelField("Selected Objects :"); | |
_selectedObjects = Selection.gameObjects; | |
if (_selectedObjects.Length == 0) | |
EditorGUILayout.LabelField("You need to select at least one object.", | |
_errorStyle); | |
_scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); | |
EditorGUI.BeginDisabledGroup(true); | |
foreach (var selectedObject in _selectedObjects) | |
{ | |
EditorGUILayout.ObjectField(selectedObject.name, selectedObject, | |
typeof(GameObject), false); | |
} | |
EditorGUI.EndDisabledGroup(); | |
EditorGUILayout.EndScrollView(); | |
if (GUILayout.Button("Replace Duplicate Meshes") && _selectedObjects.Length > 0) | |
ReplaceDuplicateMeshes(); | |
} | |
private void ReplaceDuplicateMeshes() | |
{ | |
var meshFilters = new HashSet<MeshFilter>(); | |
foreach (var selectedObject in _selectedObjects) | |
{ | |
var selectedObjectMeshFilters = selectedObject.GetComponentsInChildren<MeshFilter>(); | |
meshFilters.UnionWith(selectedObjectMeshFilters); | |
} | |
foreach (var meshFilterA in meshFilters) | |
{ | |
foreach (var meshFilterB in meshFilters) | |
{ | |
if (IsACopy(meshFilterA, meshFilterB)) | |
meshFilterA.sharedMesh = meshFilterB.sharedMesh; | |
} | |
} | |
} | |
private bool IsACopy(MeshFilter meshFilterA, MeshFilter meshFilterB) | |
{ | |
return meshFilterA.sharedMesh.vertexCount.Equals(meshFilterB.sharedMesh.vertexCount) | |
&& meshFilterA.sharedMesh.triangles.Length.Equals(meshFilterB.sharedMesh.triangles.Length) | |
&& meshFilterA.sharedMesh.bounds.Equals(meshFilterB.sharedMesh.bounds); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment