using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Debugging { public class DuplicateManager : MonoBehaviour { private void Start() { var objects = FindObjectsOfType(); var objectsAtPos = new Dictionary>(); Debug.Log($"Found {objects.Length} GameObjects"); var i = 0; foreach (var o in objects) { var pos = o.transform.position; if (!objectsAtPos.ContainsKey(pos)) { var l = new List {o.gameObject}; objectsAtPos[pos] = l; } else { objectsAtPos[pos].Add(o.gameObject); } i++; if (i % 100 == 0) { //Debug.Log($"{i}/{objects.Length} objects done!"); } } Debug.Log("Done sorting"); var objs = objectsAtPos.Values.Where(l => l.Count > 1); var enumerable = objs as List[] ?? objs.ToArray(); Debug.LogWarning($"{enumerable.Count()} gameobjects at exact same position"); Debug.Log("Deleting objects.."); var deleteCounter = 0; var skipCounter = 0; foreach (var o in enumerable) { var rMap = new Dictionary>(); foreach (var d in o) { var rot = d.transform.rotation; if (rMap.ContainsKey(rot)) rMap[rot].Add(d); else rMap[rot] = new List {d}; //Destroy(d); } var samePosAndRot = rMap.Values.Max(v => v.Count); Debug.Log($"max same pos and rot = {samePosAndRot}"); if (samePosAndRot < 2) continue; var resultsWithMax = rMap.Values.Where(l => l.Count == samePosAndRot); foreach (var r in resultsWithMax) { Debug.Log($"Names: {string.Join(",", r.Select(x => x.name))}"); if (r.Aggregate((result, item) => { if (result == null) return null; return result.name.Equals(item.name) ? item : null; }) != null) for (var index = 1; index < r.Count; index++) { var gameObject1 = r[index]; if (gameObject1.transform.childCount == 0) { Destroy(gameObject1); } else { Debug.LogError($"Did not destroy {gameObject1.name}"); skipCounter++; } deleteCounter++; } } } Debug.LogWarning($"Deleted {deleteCounter} items!"); Debug.LogWarning($"Skipped {skipCounter} items!"); } } }