1 using System.Collections;
2 using System.Collections.Generic;
3 using UnityEngine;
4
5 public class test : MonoBehaviour
6 {
7 public Transform parent; //这个parent下面挂着四个物体
8 public GameObject ObjCenter; //这个物体是为了说明清楚计算后的中心点的位置的
9 // Use this for initialization
10 void Start()
11 {
12
13 }
14
15 // Update is called once per frame
16 void Update()
17 {
18 ObjCenter.transform.position = GetCenter(parent);
19 }
20 //计算模型的中心点
21 public static Vector3 GetCenter(Transform tt)
22 {
23
24 Transform parent = tt;
25
26 Vector3 postion = parent.position;
27
28 Quaternion rotation = parent.rotation;
29
30 Vector3 scale = parent.localScale;
31
32 parent.position = Vector3.zero;
33
34 parent.rotation = Quaternion.Euler(Vector3.zero);
35
36 parent.localScale = Vector3.one;
37
38 Vector3 center = Vector3.zero;
39
40 Renderer[] renders = parent.GetComponentsInChildren<Renderer>();
41
42 foreach (Renderer child in renders)
43 {
44 center += child.bounds.center;
45 }
46
47 center /= parent.GetComponentsInChildren<Renderer>().Length;
48
49 Bounds bounds = new Bounds(center, Vector3.zero);
50
51 foreach (Renderer child in renders)
52 {
53
54 bounds.Encapsulate(child.bounds);
55
56 }
57
58 parent.position = postion;
59
60 parent.rotation = rotation;
61
62 parent.localScale = scale;
63
64 return bounds.center + parent.position;
65 }
66 }