Add Editor script of BoxCollider to irregular model (sub object)
![Add Editor script of BoxCollider to irregular model (sub object) Add Editor script of BoxCollider to irregular model (sub object)](http://up-free-imgs.azimiao.com/wp-content/uploads/2017/10/imageUnityOk02.jpg)
preface
realization
1. Key methods
-
Selection.activeGameObject
Under the UnityEditor namespace, get the selected game object in the hierarchy view. -
Render.bounds
The rendering bounding box of MeshRender (or other Render components) of GameObject, that is, the actual size. -
Transform.InverseTransformPoint
Converts world coordinates to local coordinates.
2. Complete script
using UnityEngine; using UnityEditor; public class MyTools : Editor { [MenuItem("MyTools/AddBoxCollider")] static void AddBoxCollider() { if (Selection.activeGameObject == null) { #if UNITY_EDITOR Debug. Log ("<color=red>MyTools/AddBoxCollider: objects not selected</color>"); #endif return; } Transform target = Selection.activeGameObject.transform; Vector3 center = Vector3.zero; //Note that the components obtained by GetComponentsInChildren include the components attached to the parent object var renders = target.GetComponentsInChildren<Renderer>(); for (int i = 0; i < renders.Length; i++) { //Bounds.center is the world coordinate of the center point of the rendering boundary center += renders[i].bounds.center; } //Find the average center point, similar to (point A+point B)/2 as the center point of the two-point line. center /= renders.Length; //Create a bounding box whose center is the calculated average center point. Bounds bounds = new Bounds(center, Vector3.zero); for (int i = 0; i < renders.Length; i++) { //Make the bounding box wrap the RendererBounds of the sub object bounds.Encapsulate(renders[i].bounds); } BoxCollider boxCollider = target.gameObject.AddComponent<BoxCollider>(); //Bounds.center is the world coordinate, which needs to be converted to the local coordinate of the parent object boxCollider.center = target.InverseTransformPoint(bounds.center); //After the parent object is scaled, the length represented by size 1 of boxCollider will also be scaled, 1m ->0.1m //Bounds is different. It is always the standard 1m, so it needs to be divided by the parent object scaling. boxCollider.size = bounds.size / target.localScale.z; } }
effect
References
-
[Header] [Unity] Unity Japan UnityChanSD Role