DuplicateManager.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. public class DuplicateManager : MonoBehaviour
  6. {
  7. private void Start()
  8. {
  9. var objects = FindObjectsOfType<MeshRenderer>();
  10. var objectsAtPos = new Dictionary<Vector3, List<GameObject>>();
  11. Debug.Log($"Found {objects.Length} GameObjects");
  12. var i = 0;
  13. foreach (var o in objects)
  14. {
  15. var pos = o.transform.position;
  16. if (!objectsAtPos.ContainsKey(pos))
  17. {
  18. var l = new List<GameObject> {o.gameObject};
  19. objectsAtPos[pos] = l;
  20. }
  21. else
  22. {
  23. objectsAtPos[pos].Add(o.gameObject);
  24. }
  25. i++;
  26. if (i % 100 == 0)
  27. {
  28. //Debug.Log($"{i}/{objects.Length} objects done!");
  29. }
  30. }
  31. Debug.Log($"Done sorting");
  32. var objs = objectsAtPos.Values.Where(l => l.Count > 1);
  33. var enumerable = objs as List<GameObject>[] ?? objs.ToArray();
  34. Debug.LogWarning($"{enumerable.Count()} gameobjects at exact same position");
  35. Debug.Log("Deleting objects..");
  36. int deleteCounter = 0;
  37. int skipCounter = 0;
  38. foreach (var o in enumerable)
  39. {
  40. var rMap = new Dictionary<Quaternion, List<GameObject>>();
  41. foreach (var d in o)
  42. {
  43. var rot = d.transform.rotation;
  44. if (rMap.ContainsKey(rot))
  45. {
  46. rMap[rot].Add(d);
  47. }
  48. else
  49. {
  50. rMap[rot] = new List<GameObject> {d};
  51. }
  52. //Destroy(d);
  53. }
  54. var samePosAndRot = rMap.Values.Max(v => v.Count);
  55. Debug.Log($"max same pos and rot = {samePosAndRot}");
  56. if (samePosAndRot < 2) continue;
  57. var resultsWithMax = rMap.Values.Where(l => l.Count == samePosAndRot);
  58. foreach (var r in resultsWithMax)
  59. {
  60. Debug.Log($"Names: {string.Join(",", r.Select(x => x.name))}");
  61. if (r.Aggregate((result, item) =>
  62. {
  63. if (result == null) return null;
  64. else return result.name.Equals(item.name) ? item : null;
  65. }) != null)
  66. {
  67. for (var index = 1; index < r.Count; index++)
  68. {
  69. var gameObject1 = r[index];
  70. if (gameObject1.transform.childCount == 0)
  71. {
  72. Destroy(gameObject1);
  73. }
  74. else
  75. {
  76. Debug.LogError($"Did not destroy {gameObject1.name}");
  77. skipCounter++;
  78. }
  79. deleteCounter++;
  80. }
  81. }
  82. }
  83. }
  84. Debug.LogWarning($"Deleted {deleteCounter} items!");
  85. Debug.LogWarning($"Skipped {skipCounter} items!");
  86. }
  87. }