Unity 游戏框架搭建 (九) 减少加班利器-QConsole

转载请注明地址:凉鞋的笔记

为毛要实现这个工具?
  1.在我小时候,每当游戏在真机运行时,我们看到的日志是这样的。

01.png

没高亮啊,还有乱七八糟的堆栈信息,好干扰日志查看,好影响心情。

2.还有就是必须始终连着usb线啊,我想要想躺着测试。。。
以上种种原因,QConsole诞生了。

如何使用?

使用方式和QLog一样,在初始化出调用,简单的一句。

QConsole.Instance();  

就好了,使用之后效果是这样的。

02.png

在Editor模式下,F1控制开关。
在真机上需要在屏幕上同时按下五个手指就可以控制开关了。(本来考虑11个手指萌一下的)。

实现思路:
  1.首先要想办法获取Log,这个和上一篇介绍的QLog一样,需要使用Application.logMessageReceived这个api。
  2.获取到的Log信息要存在一个Queue或者List中,然后把Log输出到屏幕上就ok了。
  3.输出到屏幕上使用的是OnGUI回调和 GUILayout.Window这个api, 总共三步。

贴上代码:

QConsole实现

sing UnityEngine;  
#if UNITY_EDITOR
using UnityEditor;  
#endif
using System.Collections;  
using System;  
using System.Collections.Generic;

namespace QFramework {  
/// <summary>
/// 控制台GUI输出类
/// 包括FPS,内存使用情况,日志GUI输出
/// </summary>
public class QConsole : QSingleton<QConsole>
{

    struct ConsoleMessage
    {
        public readonly string  message;
        public readonly string  stackTrace;
        public readonly LogType type;

        public ConsoleMessage (string message, string stackTrace, LogType type)
        {
            this.message    = message;
            this.stackTrace = stackTrace;
            this.type       = type;
        }
    }

    /// <summary>
    /// Update回调
    /// </summary>
    public delegate void OnUpdateCallback();
    /// <summary>
    /// OnGUI回调
    /// </summary>
    public delegate void OnGUICallback();

    public OnUpdateCallback onUpdateCallback = null;
    public OnGUICallback onGUICallback = null;
    /// <summary>
    /// FPS计数器
    /// </summary>
    private QFPSCounter fpsCounter = null;
    /// <summary>
    /// 内存监视器
    /// </summary>
    private QMemoryDetector memoryDetector = null;
    private bool showGUI = true;
    List<ConsoleMessage> entries = new List<ConsoleMessage>();
    Vector2 scrollPos;
    bool scrollToBottom = true;
    bool collapse;
    bool mTouching = false;

    const int margin = 20;
    Rect windowRect = new Rect(margin + Screen.width * 0.5f, margin, Screen.width * 0.5f - (2 * margin), Screen.height - (2 * margin));

    GUIContent clearLabel    = new GUIContent("Clear",    "Clear the contents of the console.");
    GUIContent collapseLabel = new GUIContent("Collapse", "Hide repeated messages.");
    GUIContent scrollToBottomLabel = new GUIContent("ScrollToBottom", "Scroll bar always at bottom");


    private QConsole()
    {
        this.fpsCounter = new QFPSCounter(this);
        this.memoryDetector = new QMemoryDetector(this);
        //        this.showGUI = App.Instance().showLogOnGUI;
        QApp.Instance().onUpdate += Update;
        QApp.Instance().onGUI += OnGUI;
        Application.logMessageReceived += HandleLog;

    }

    ~QConsole()
    {
        Application.logMessageReceived -= HandleLog;
    }


    void Update()
    {
        #if UNITY_EDITOR
        if (Input.GetKeyUp(KeyCode.F1))
            this.showGUI = !this.showGUI;
        #elif UNITY_ANDROID
        if (Input.GetKeyUp(KeyCode.Escape))
            this.showGUI = !this.showGUI;
        #elif UNITY_IOS
        if (!mTouching && Input.touchCount == 4)
        {
            mTouching = true;
            this.showGUI = !this.showGUI;
        } else if (Input.touchCount == 0){
            mTouching = false;
        }
        #endif

        if (this.onUpdateCallback != null)
            this.onUpdateCallback();
    }

    void OnGUI()
    {
        if (!this.showGUI)
            return;

        if (this.onGUICallback != null)
            this.onGUICallback ();

        if (GUI.Button (new Rect (100, 100, 200, 100), "清空数据")) {
            PlayerPrefs.DeleteAll ();
            #if UNITY_EDITOR
            EditorApplication.isPlaying = false;
            #else
            Application.Quit();
            #endif
        }
        windowRect = GUILayout.Window(123456, windowRect, ConsoleWindow, "Console");
    }


    /// <summary>
    /// A window displaying the logged messages.
    /// </summary>
    void ConsoleWindow (int windowID)
    {
        if (scrollToBottom) {
            GUILayout.BeginScrollView (Vector2.up * entries.Count * 100.0f);
        }
        else {
            scrollPos = GUILayout.BeginScrollView (scrollPos);
        }
        // Go through each logged entry
        for (int i = 0; i < entries.Count; i++) {
            ConsoleMessage entry = entries[i];
            // If this message is the same as the last one and the collapse feature is chosen, skip it
            if (collapse && i > 0 && entry.message == entries[i - 1].message) {
                continue;
            }
            // Change the text colour according to the log type
            switch (entry.type) {
                case LogType.Error:
                case LogType.Exception:
                    GUI.contentColor = Color.red;
                    break;
                case LogType.Warning:
                    GUI.contentColor = Color.yellow;
                    break;
                default:
                    GUI.contentColor = Color.white;
                    break;
            }
            if (entry.type == LogType.Exception)
            {
                GUILayout.Label(entry.message + " || " + entry.stackTrace);
            } else {
                GUILayout.Label(entry.message);
            }
        }
        GUI.contentColor = Color.white;
        GUILayout.EndScrollView();
        GUILayout.BeginHorizontal();
        // Clear button
        if (GUILayout.Button(clearLabel)) {
            entries.Clear();
        }
        // Collapse toggle
        collapse = GUILayout.Toggle(collapse, collapseLabel, GUILayout.ExpandWidth(false));
        scrollToBottom = GUILayout.Toggle (scrollToBottom, scrollToBottomLabel, GUILayout.ExpandWidth (false));
        GUILayout.EndHorizontal();
        // Set the window to be draggable by the top title bar
        GUI.DragWindow(new Rect(0, 0, 10000, 20));
    }

    void HandleLog (string message, string stackTrace, LogType type)
    {
        ConsoleMessage entry = new ConsoleMessage(message, stackTrace, type);
        entries.Add(entry);
      }
  }
}

QFPSCounter

using UnityEngine;  
using System.Collections;

namespace QFramework {  
/// <summary>
/// 帧率计算器
/// </summary>
public class QFPSCounter
{
    // 帧率计算频率
    private const float calcRate = 0.5f;
    // 本次计算频率下帧数
    private int frameCount = 0;
    // 频率时长
    private float rateDuration = 0f;
    // 显示帧率
    private int fps = 0;

    public QFPSCounter(QConsole console)
    {
        console.onUpdateCallback += Update;
        console.onGUICallback += OnGUI;
    }

    void Start()
    {
        this.frameCount = 0;
        this.rateDuration = 0f;
        this.fps = 0;
    }

    void Update()
    {
        ++this.frameCount;
        this.rateDuration += Time.deltaTime;
        if (this.rateDuration > calcRate)
        {
            // 计算帧率
            this.fps = (int)(this.frameCount / this.rateDuration);
            this.frameCount = 0;
            this.rateDuration = 0f;
        }
    }

    void OnGUI()
    {
        GUI.color = Color.black;
        GUI.Label(new Rect(80, 20, 120, 20),"fps:" + this.fps.ToString());      
      }
  }
}

QMemoryDetector

using UnityEngine;  
using System.Collections;


namespace QFramework {  
/// <summary>
/// 内存检测器,目前只是输出Profiler信息
/// </summary>
public class QMemoryDetector 
{
    private readonly static string TotalAllocMemroyFormation = "Alloc Memory : {0}M";
    private readonly static string TotalReservedMemoryFormation = "Reserved Memory : {0}M";
    private readonly static string TotalUnusedReservedMemoryFormation = "Unused Reserved: {0}M";
    private readonly static string MonoHeapFormation = "Mono Heap : {0}M";
    private readonly static string MonoUsedFormation = "Mono Used : {0}M";
    // 字节到兆
    private float ByteToM = 0.000001f;

    private Rect allocMemoryRect;
    private Rect reservedMemoryRect;
    private Rect unusedReservedMemoryRect;
    private Rect monoHeapRect;
    private Rect monoUsedRect;

    private int x = 0;
    private int y = 0;
    private int w = 0;
    private int h = 0;

    public QMemoryDetector(QConsole console)
    {
        this.x = 60;
        this.y = 60;
        this.w = 200;
        this.h = 20;

        this.allocMemoryRect = new Rect(x, y, w, h);
        this.reservedMemoryRect = new Rect(x, y + h, w, h);
        this.unusedReservedMemoryRect = new Rect(x, y + 2 * h, w, h);
        this.monoHeapRect = new Rect(x, y + 3 * h, w, h);
        this.monoUsedRect = new Rect(x, y + 4 * h, w, h);

        console.onGUICallback += OnGUI;
    }

    void OnGUI()
    {
        GUI.Label(this.allocMemoryRect, 
            string.Format(TotalAllocMemroyFormation, Profiler.GetTotalAllocatedMemory() * ByteToM));
        GUI.Label(this.reservedMemoryRect, 
            string.Format(TotalReservedMemoryFormation, Profiler.GetTotalReservedMemory() * ByteToM));
        GUI.Label(this.unusedReservedMemoryRect, 
            string.Format(TotalUnusedReservedMemoryFormation, Profiler.GetTotalUnusedReservedMemory() * ByteToM));
        GUI.Label(this.monoHeapRect,
            string.Format(MonoHeapFormation, Profiler.GetMonoHeapSize() * ByteToM));
        GUI.Label(this.monoUsedRect,
            string.Format(MonoUsedFormation, Profiler.GetMonoUsedSize() * ByteToM));
        }
    }
}

注意事项:

1.和上一篇介绍的QLog一样,需要依赖上上篇文章介绍的QApp。
  2.QConsole初步实现来自于开源Unity插件Unity-WWW-Wrapper中的Console.cs.在此基础上添加了ScrollToBottom选项。因为这个插件的控制台不支持滚动显示Log,需要拖拽右边的scrollBar,很不方便。
  3.Unity-WWW-wrapper非常不稳定,建议大家不要使用。倒是感兴趣的同学可以研究下实现,贴上地址:https://www.assetstore.unity3d.com/en/#!/content/19116

欢迎讨论!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355

推荐阅读更多精彩内容