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中如何通过Animator动画...
这篇文章主要介绍了Unity3D如何播放游戏视频,具有一定借鉴价...
这篇文章给大家分享的是有关Unity3D各平台路径是什么的内容。...
小编给大家分享一下Unity3D如何实现移动平台上的角色阴影,希...
如何解析基于Unity3D的平坦四叉树地形与Virtual Texture的分...
这篇文章主要介绍Unity3D如何实现动态分辨率降低渲染开销,文...