注意仅能在编辑器下才能使用该方法
实现方式依靠UnityEditor.Tools提供的参数,具体实现如下:
- 获取单个物体的中心坐标
public static Vector3 GetGameObjectCenter(GameObject gameObject)
{// 选中物体Selection.activeObject = gameObject;// 记录当前Scene窗口的Tool Handle状态var curPivotMode = Tools.pivotMode;// 将Handle转成Center模式Tools.pivotMode = PivotMode.Center;// 获取Scene的ViewSceneView view = SceneView.lastActiveSceneView;// 聚焦并重绘场景view.Focus();view.Repaint();// 保存当前handle的坐标,即为center坐标var center = Tools.handlePosition;// 复原状态Selection.objects = null;Tools.pivotMode = curPivotMode;return center;
}
- 获取一组物体的中心坐标
public static Vector3 GetGameObjectsCenter(GameObject[] gameObjects)
{// 选中所有物体Selection.objects = gameObjects;// 记录当前Scene窗口的Tool Handle状态var curPivotMode = Tools.pivotMode;// 将Handle转成Center模式Tools.pivotMode = PivotMode.Center;// 获取Scene的ViewSceneView view = SceneView.lastActiveSceneView;// 聚焦并重绘场景view.Focus();view.Repaint();// 保存当前handle的坐标,即为center坐标var center = Tools.handlePosition;// 复原状态Selection.objects = null;Tools.pivotMode = curPivotMode;return center;
}