最近在处理酷跑类型游戏时,遇到一个功能需求:需要在摄像机实时追踪角色显示(Game)的同时,Scene同时实时显示NPC的位置状态等信息?
这个问题有三种解决方法,各有利弊:
1)使用unity系统内置的方法,此时直接激活即可:快速三次点击目标游戏对象即可。
这种方法的缺点是不灵活,一旦鼠标有其他动作,就会打断追踪;
方法2/3需要自己来扩展编辑器(思想是一样的):
2)打开一个新面板,用来驱动刷新:
public class SceneRealTimeFocusEditorWindow : EditorWindow
{
SceneView.OnSceneFunc _delegate;
static SceneRealTimeFocusEditorWindow _windowInstance;
[MenuItem("Window/RealTimeFocus")]
static void RealTimeFocus()
{
if (_windowInstance == null)
{
_windowInstance = EditorWindow.GetWindow(typeof(SceneRealTimeFocusEditorWindow)) as SceneRealTimeFocusEditorWindow;
_windowInstance._delegate = new SceneView.OnSceneFunc(OnSceneFunc);
SceneView.onSceneGUIDelegate += _windowInstance._delegate;
}
}
void OnDestroy()
{
if (_delegate != null)
{
SceneView.onSceneGUIDelegate -= _delegate;
}
}
public static void OnSceneFunc(SceneView sceneView)
{
_windowInstance.CustomSceneGUI(sceneView);
}
void CustomSceneGUI(SceneView sceneView)
{
if (Selection.activeTransform != null && Selection.activeTransform.root != null && active)
{
SceneView.lastActiveSceneView.pivot = Selection.activeTransform.position;
//SceneView.lastActiveSceneView.Repaint();
SceneView.RepaintAll();
}
}
private bool active = false;
void OnGUI()
{
active = GUILayout.Toggle(active, "Active RealTimeScene");
}
}
此种方法的优点:打开面板,可实现当前选中的任意对象的Scene实时追踪
3)Scene中的按钮扩展:
[CustomEditor(typeof(MonoBehaviour), true)]
public class SceneRealTimeFocusEditor : Editor
{
public void OnEnable()
{
active = false;
}
public void OnDisable()
{
active = false;
}
private bool active = false;
void OnSceneGUI()
{
if (Selection.activeTransform != null)
{
Handles.BeginGUI();
GUILayout.BeginArea(new Rect(0, 0, 200, 200));
if (!active)
{
if (GUILayout.Button("Active Real Time Trace", GUILayout.Height(30)))
{
active = true;
}
}
else
{
if (GUILayout.Button("Close Real Time Trace", GUILayout.Height(30)))
{
active = false;
}
}
GUILayout.EndArea();
Handles.EndGUI();
if (active)
{
SceneView.lastActiveSceneView.pivot = Selection.activeTransform.position;
SceneView.lastActiveSceneView.Repaint();
}
}
}
}
本方法的缺点是:若针对MonoBehaviour及其子类,则当选中的目标对象有多个子物体、多个基于monobehavoiur的component时,按钮显示会有问题;若不针对MonoBehaviour及其子类,则只能针对特定类型物体选中时实时追踪。