12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- public class DuplicateManager : MonoBehaviour
- {
- private void Start()
- {
- var objects = FindObjectsOfType<MeshRenderer>();
- var objectsAtPos = new Dictionary<Vector3, List<GameObject>>();
- 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<GameObject> {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<GameObject>[] ?? objs.ToArray();
- Debug.LogWarning($"{enumerable.Count()} gameobjects at exact same position");
- Debug.Log("Deleting objects..");
- int deleteCounter = 0;
- int skipCounter = 0;
-
- foreach (var o in enumerable)
- {
- var rMap = new Dictionary<Quaternion, List<GameObject>>();
- foreach (var d in o)
- {
- var rot = d.transform.rotation;
- if (rMap.ContainsKey(rot))
- {
- rMap[rot].Add(d);
- }
- else
- {
- rMap[rot] = new List<GameObject> {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;
- else 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!");
- }
- }
|