123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- 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<GameObject> collidersObjects = new Queue<GameObject>();
- 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);
- }
- }
- }
- }
- /// <summary>
- /// 添加碰撞体
- /// </summary>
- /// <param name="gameObject"></param>
- 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<Collider>())
- gameObject.AddComponent<BoxCollider>();
- if (gameObject.GetComponent<BoxCollider>())
- {
- gameObject.GetComponent<BoxCollider>().size = itemBound.size;
- gameObject.GetComponent<BoxCollider>().center = itemBound.center;
- }
- }
- /// <summary>
- /// 获得对象的最小包围盒
- /// </summary>
- public static Bounds GetLocalBounds(GameObject target)
- {
- Renderer[] mfs = target.GetComponentsInChildren<Renderer>();
- Bounds bounds = new Bounds();
- if (mfs.Length != 0)
- {
- bounds = mfs[0].bounds;
- foreach (Renderer mf in mfs)
- {
- bounds.Encapsulate(mf.bounds);
- }
- }
- return bounds;
- }
- }
|