1
0

DuplicateManager.cs 2.9 KB

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