BatchGenerateBoxColliders.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Collections.Generic;
  2. using UnityEditor;
  3. using UnityEngine;
  4. public class BatchGenerateBoxColliders : Editor
  5. {
  6. [MenuItem("添加碰撞体/创建")]
  7. static void AddSingleBoxCollider()
  8. {
  9. for (int i = 0; i < Selection.gameObjects.Length; i++)
  10. {
  11. AddGameObjectCollider(Selection.gameObjects[i]);
  12. }
  13. }
  14. [MenuItem("添加碰撞体/递归创建")]
  15. static void AddMultipleBoxCollider()
  16. {
  17. for (int i = 0; i < Selection.gameObjects.Length; i++)
  18. {
  19. Queue<GameObject> collidersObjects = new Queue<GameObject>();
  20. collidersObjects.Enqueue(Selection.gameObjects[i].transform.GetChild(0).gameObject);
  21. while (collidersObjects.Count != 0)
  22. {
  23. GameObject parent = collidersObjects.Dequeue();
  24. AddGameObjectCollider(parent);
  25. for (int j = 0; j < parent.transform.childCount; j++)
  26. {
  27. collidersObjects.Enqueue(parent.transform.GetChild(j).gameObject);
  28. }
  29. }
  30. }
  31. }
  32. /// <summary>
  33. /// 添加碰撞体
  34. /// </summary>
  35. /// <param name="gameObject"></param>
  36. public static void AddGameObjectCollider(GameObject gameObject)
  37. {
  38. Vector3 pos = gameObject.transform.localPosition;
  39. Quaternion qt = gameObject.transform.localRotation;
  40. Vector3 ls = gameObject.transform.localScale;
  41. gameObject.transform.position = Vector3.zero;
  42. gameObject.transform.eulerAngles = Vector3.zero;
  43. gameObject.transform.localScale = Vector3.one;
  44. //获取物体的最小包围盒
  45. Bounds itemBound = GetLocalBounds(gameObject);
  46. gameObject.transform.localPosition = pos;
  47. gameObject.transform.localRotation = qt;
  48. gameObject.transform.localScale = ls;
  49. //parent = null;
  50. if (!gameObject.GetComponent<Collider>())
  51. gameObject.AddComponent<BoxCollider>();
  52. if (gameObject.GetComponent<BoxCollider>())
  53. {
  54. gameObject.GetComponent<BoxCollider>().size = itemBound.size;
  55. gameObject.GetComponent<BoxCollider>().center = itemBound.center;
  56. }
  57. }
  58. /// <summary>
  59. /// 获得对象的最小包围盒
  60. /// </summary>
  61. public static Bounds GetLocalBounds(GameObject target)
  62. {
  63. Renderer[] mfs = target.GetComponentsInChildren<Renderer>();
  64. Bounds bounds = new Bounds();
  65. if (mfs.Length != 0)
  66. {
  67. bounds = mfs[0].bounds;
  68. foreach (Renderer mf in mfs)
  69. {
  70. bounds.Encapsulate(mf.bounds);
  71. }
  72. }
  73. return bounds;
  74. }
  75. }