1.获取中心点
public Vector3 GetCenter(GameObject target)
{
Renderer[] mrs = target.gameObject.GetComponentsInChildren<Renderer>();
Vector3 center = target.transform.position;
if (mrs.Length != 0)
{
Bounds bounds = new Bounds(center, Vector3.zero);
foreach (Renderer mr in mrs)
{
bounds.Encapsulate(mr.bounds);
}
center = bounds.center;
}
return center;
}
2.获取包围盒(通过Renderer)
public Bounds GetBounds(GameObject target, bool include_children = true)
{
Renderer[] mrs = target.gameObject.GetComponentsInChildren<Renderer>();
Vector3 center = target.transform.position;
Bounds bounds = new Bounds(center, Vector3.zero);
if (include_children)
{
if (mrs.Length != 0)
{
foreach (Renderer mr in mrs)
{
bounds.Encapsulate(mr.bounds);
}
}
}
else
{
Renderer rend = target.GetComponentInChildren<Renderer>();
if (rend)
{
bounds = rend.bounds;
}
}
return bounds;
}
3.获取包围盒(通过MeshFilter)
public Bounds GetLocalBounds(GameObject target, bool include_children = true)
{
MeshFilter[] mfs = target.gameObject.GetComponentsInChildren<MeshFilter>();
Vector3 center = target.transform.localPosition;
Bounds bounds = new Bounds(center, Vector3.zero);
if (include_children)
{
if (mfs.Length != 0)
{
foreach (MeshFilter mf in mfs)
{
if (mf.mesh)
{
bounds.Encapsulate(mf.mesh.bounds);
}
}
}
}
else
{
MeshFilter mf = target.GetComponentInChildren<MeshFilter>();
if (mf && mf.mesh)
{
bounds = mf.mesh.bounds;
}
}
return bounds;
}