How to switch on/off statistics panel in editor wh

2019-06-12 05:26发布

问题:

I want to switch this panel on/off by C# script while playing. Is this possible? Haven't found any Editor API functions for this.

回答1:

You can do it with reflection. Modified similar answer I made long ago. Below is a working set/get stats function. Tested with Unity 5.4.0f1. I put the Unity version so that people won't complain when it stops working. Unity's update can break this anytime if they rename any of the variables.

  • GameView = A class that is used to represent Unity GameView tab in the Editor.
  • GetMainGameView = static function that returns current GameView instance.
  • m_Stats = a boolean variable that is used to determine if stats should be displayed or not.

Code:

//Show/Hide stats
void showStats(bool enableStats)
{
    Assembly asm = Assembly.GetAssembly(typeof(Editor));
    Type type = asm.GetType("UnityEditor.GameView");
    if (type != null)
    {
        MethodInfo gameViewFunction = type.GetMethod("GetMainGameView", BindingFlags.Static |
            BindingFlags.NonPublic);

        object gameViewInstance = gameViewFunction.Invoke(null, null);


        FieldInfo getFieldInfo = type.GetField("m_Stats", BindingFlags.Instance |
                                               BindingFlags.NonPublic | BindingFlags.Public);

        getFieldInfo.SetValue(gameViewInstance, enableStats);
    }
}

//Returns true if stats is enabled
bool statsIsEnabled()
{
    Assembly asm = Assembly.GetAssembly(typeof(Editor));
    Type type = asm.GetType("UnityEditor.GameView");
    if (type != null)
    {
        MethodInfo gameViewFunction = type.GetMethod("GetMainGameView", BindingFlags.Static |
            BindingFlags.NonPublic);

        object gameViewInstance = gameViewFunction.Invoke(null, null);


        FieldInfo getFieldInfo = type.GetField("m_Stats", BindingFlags.Instance |
                                               BindingFlags.NonPublic | BindingFlags.Public);

        return (bool)getFieldInfo.GetValue(gameViewInstance);
    }
    return false;
}

Usage:

//Show stats
showStats(true);

//Hide stats
showStats(false);

//Read stats
bool stats = statsIsEnabled();


回答2:

No it's not possible, unless you are a persistent hacker. GameView is an internal class, not accessible for editor scripting. But hey, there always is an option for good ol' reflection. This question will set you on the right track: http://answers.unity3d.com/questions/179775/game-window-size-from-editor-window-in-editor-mode.html