Unity3d自动计算所有包围盒的中心点

在Unity开发中,相信程序有时候拿到的模型 transform中心点远离模型十万八千里,美术在做场景的时候可能会出现这个,与其相信美术或者策划,我觉得程序要更相信自己
下面我们来看下在Unity自动计算所有包围盒的中心点来使模型transform中心点居中

[MenuItem ("Tools/SetModelCenter")]
public static void SetModelCenter()
{
    Transform trans = Selection.activeGameObject.transform;
    Vector3 postion = trans.position;
    Quaternion rotation = trans.rotation;
    Vector3 scale = trans.localScale;
    
    trans.position = Vector3.zero;
    trans.rotation = Quaternion.Euler(Vector3.zero);
    trans.localScale = Vector3.one;
    Vector3 center = Vector3.zero;
    
    Renderer[] renders = trans.GetComponentsInChildren<Renderer>();
    foreach (Renderer child in renders)
    {
        center += child.bounds.center;
    }
    center /= trans.GetComponentsInChildren().Length;
    Bounds bounds = new Bounds(center, Vector3.zero);
    foreach (Renderer child in renders)
    {
        bounds.Encapsulate(child.bounds);
    }

    trans.position = postion;
    trans.rotation = rotation;
    trans.localScale = scale;
    
    foreach(Transform t in trans)
    {
        t.position = t.position - bounds.center;
    }   
    trans.transform.position = bounds.center + trans.position;
}

你可能感兴趣的:(Unity3D)