DuplicateManager.cs 3.3 KB

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