1. 程式人生 > >unity 獲取包圍盒

unity 獲取包圍盒

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;

        }