注意僅能在編輯器下才能使用該方法
實現方式依靠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;
}