代码如下可直接调用
MeshTool.SpawnCollider(mode);
using UnityEngine;
public class MeshTool
{
public static Bounds SpawnCollider(Transform target)
{
Vector3 pMax = Vector3.zero;
Vector3 pMin = Vector3.zero;
Vector3 center = Vector3.zero;
Vector3 oldPos = target.transform.position;
Quaternion oldQua = target.transform.rotation;
Vector3 oldScale = target.transform.localScale;
target.transform.position = Vector3.zero;
target.transform.rotation = Quaternion.identity;
target.transform.localScale = Vector3.one;
Bounds bounds = CalcBounds(target, ref pMax, ref pMin, ref center);
BoxCollider collider = target.GetComponent<BoxCollider>();
if (collider == null)
{
collider = target.gameObject.AddComponent<BoxCollider>();
}
collider.center = bounds.center;
collider.size = bounds.size;
target.transform.position = oldPos;
target.transform.rotation = oldQua;
target.transform.localScale = oldScale;
return bounds;
}
private static Bounds CalcBounds(Transform obj, ref Vector3 pMax, ref Vector3 pMin, ref Vector3 center)
{
Renderer meshRenderer = obj.GetComponent<Renderer>();
if (meshRenderer != null)
{
Bounds b = meshRenderer.bounds;
pMax = b.max;
pMin = b.min;
center = b.center;
}
RecursivelyCalcBounds(obj.transform, ref pMax, ref pMin);
CalculateCenter(pMax, pMin, out center, ref pMax, ref pMin);
Vector3 size = new Vector3(pMax.x - pMin.x, pMax.y - pMin.y, pMax.z - pMin.z);
Bounds bound = new Bounds(center, size);
return bound;
}
private static void CalculateCenter(Vector3 max, Vector3 min, out Vector3 center, ref Vector3 pMax, ref Vector3 pMin)
{
float xc = (pMax.x + pMin.x) / 2f;
float yc = (pMax.y + pMin.y) / 2f;
float zc = (pMax.z + pMin.z) / 2f;
center = new Vector3(xc, yc, zc);
}
private static void RecursivelyCalcBounds(Transform obj, ref Vector3 pMax, ref Vector3 pMin)
{
if (obj.transform.childCount <= 0)
{
return;
}
foreach (Transform item in obj)
{
Renderer m = item.GetComponent<Renderer>();
if (m != null)
{
Bounds b = m.bounds;
if (pMax.Equals(Vector3.zero) && pMin.Equals(Vector3.zero))
{
pMax = b.max;
pMin = b.min;
}
if (b.max.x > pMax.x)
{
pMax.x = b.max.x;
}
if (b.max.y > pMax.y)
{
pMax.y = b.max.y;
}
if (b.max.z > pMax.z)
{
pMax.z = b.max.z;
}
if (b.min.x < pMin.x)
{
pMin.x = b.min.x;
}
if (b.min.y < pMin.y)
{
pMin.y = b.min.y;
}
if (b.min.z < pMin.z)
{
pMin.z = b.min.z;
}
}
RecursivelyCalcBounds(item, ref pMax, ref pMin);
}
}
}