using System.Collections.Generic; using UnityEditor; using UnityEngine; public class BatchGenerateBoxColliders : Editor { [MenuItem("添加碰撞体/创建")] static void AddSingleBoxCollider() { for (int i = 0; i < Selection.gameObjects.Length; i++) { AddGameObjectCollider(Selection.gameObjects[i]); } } [MenuItem("添加碰撞体/递归创建")] static void AddMultipleBoxCollider() { for (int i = 0; i < Selection.gameObjects.Length; i++) { Queue collidersObjects = new Queue(); collidersObjects.Enqueue(Selection.gameObjects[i].transform.GetChild(0).gameObject); while (collidersObjects.Count != 0) { GameObject parent = collidersObjects.Dequeue(); AddGameObjectCollider(parent); for (int j = 0; j < parent.transform.childCount; j++) { collidersObjects.Enqueue(parent.transform.GetChild(j).gameObject); } } } } /// /// 添加碰撞体 /// /// public static void AddGameObjectCollider(GameObject gameObject) { Vector3 pos = gameObject.transform.localPosition; Quaternion qt = gameObject.transform.localRotation; Vector3 ls = gameObject.transform.localScale; gameObject.transform.position = Vector3.zero; gameObject.transform.eulerAngles = Vector3.zero; gameObject.transform.localScale = Vector3.one; //获取物体的最小包围盒 Bounds itemBound = GetLocalBounds(gameObject); gameObject.transform.localPosition = pos; gameObject.transform.localRotation = qt; gameObject.transform.localScale = ls; //parent = null; if (!gameObject.GetComponent()) gameObject.AddComponent(); if (gameObject.GetComponent()) { gameObject.GetComponent().size = itemBound.size; gameObject.GetComponent().center = itemBound.center; } } /// /// 获得对象的最小包围盒 /// public static Bounds GetLocalBounds(GameObject target) { Renderer[] mfs = target.GetComponentsInChildren(); Bounds bounds = new Bounds(); if (mfs.Length != 0) { bounds = mfs[0].bounds; foreach (Renderer mf in mfs) { bounds.Encapsulate(mf.bounds); } } return bounds; } }