## 為毛要實現這個工具?
1. 在我小時候,每當游戲在真機運行時,我們看到的日志是這樣的。

沒高亮啊,還有亂七八糟的堆棧信息,好干擾日志查看,好影響心情。
2. 還有就是必須始終連著 usb 線啊,我想要想躺著測試。。。
以上種種原因,QConsole 誕生了。
## 如何使用?
使用方式和QLog一樣,在初始化出調用,簡單的一句。
```cs
QConsole.Instance();
```
就好了,使用之后效果是這樣的。

在 Editor 模式下,F1控制開關。
在真機上需要在屏幕上同時按下五個手指就可以控制開關了。(本來考慮 11 個手指萌一下的)。
## 實現思路:
1. 首先要想辦法獲取Log,這個和上一篇介紹的 QLog 一樣,需要使用 Application.logMessageReceived 這個 api。
2. 獲取到的 Log 信息要存在一個 Queue 或者 List 中,然后把 Log 輸出到屏幕上就 ok 了。
3. 輸出到屏幕上使用的是 OnGUI 回調和 GUILayout.Window 這個 api, 總共三步。
## 貼上代碼:
QConsole實現
```cs
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
```cs
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
```cs
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。
## 歡迎討論!
轉載請注明地址:涼鞋的筆記:[liangxiegame.com](http://liangxiegame.com)
## 更多內容
* QFramework 地址:[https://github.com/liangxiegame/QFramework](https://github.com/liangxiegame/QFramework)
* QQ 交流群:[623597263](http://shang.qq.com/wpa/qunwpa?idkey=706b8eef0fff3fe4be9ce27c8702ad7d8cc1bceabe3b7c0430ec9559b3a9ce66)
* **Unity 進階小班**:
* 主要訓練內容:
* 框架搭建訓練(第一年)
* 跟著案例學 Shader(第一年)
* 副業的孵化(第二年、第三年)
* 權益、授課形式等具體詳情請查看[《小班產品手冊》](https://liangxiegame.com/master/intro):https://liangxiegame.com/master/intro
* 關注公眾號:liangxiegame 獲取第一時間更新通知及更多的免費內容。

- 正文
- Unity 游戲框架搭建 2017(一)概述
- Unity 游戲框架搭建 2017(二)單例的模板
- Unity 游戲框架搭建 2017(三)MonoBehaviour 單例的模板
- Unity 游戲框架搭建 2017(四)簡易有限狀態機
- Unity 游戲框架搭建 2017(五)簡易消息機制
- Unity 游戲框架搭建 2017 (六) 關于框架的一些好文和一些思考
- Unity 游戲框架搭建 2017 (七) 減少加班利器-QApp類
- Unity 游戲框架搭建 2017 (八) 減少加班利器-QLog
- Unity 游戲框架搭建 2017 (九) 減少加班利器-QConsole
- Unity 游戲框架搭建 2017 (十) QFramework v0.0.2小結
- Unity 游戲框架搭建 2017 (十一) 簡易 AssetBundle 打包工具 (一)
- Unity 游戲框架搭建 2017 (十二) 簡易 AssetBundle 打包工具 (二)
- Unity 游戲框架搭建 2017 (十三) 無需繼承的單例的模板
- Unity 游戲框架搭建 2017 (十四) 優雅的 QSingleton (零) QuickStart
- Unity 游戲框架搭建 2017 (十四) 優雅的 QSingleton (一) Singleton 單例實現
- Unity 游戲框架搭建 2017 (十四) 優雅的 QSingleton (二) MonoSingleton單例實現
- Unity 游戲框架搭建 2017 (十四) 優雅的 QSignleton (三) 通過屬性器實現 Singleton
- Unity 游戲框架搭建 2017 (十四) 優雅的 QSingleton (四) 屬性器實現 Mono 單例
- Unity 游戲框架搭建 2017 (十四) 優雅的 QSingleton (五) 優雅地進行GameObject命名
- Unity 游戲框架搭建 2017 (十五) 優雅的 QChain (零)
- Unity 游戲框架搭建 2017 (十六) v0.0.3 架構調整
- Unity 游戲框架搭建 2017 (十七) 靜態擴展GameObject 實現鏈式編程
- Unity 游戲框架搭建 2017 (十八) 靜態擴展 + 泛型實現 transform 的鏈式編程
- Unity 游戲框架搭建 2017 (十九) 簡易對象池
- Unity 游戲框架搭建 2017 (二十) 安全的對象池
- Unity 游戲框架搭建 2017 (二十一) 使用對象池時的一些細節
- Unity 游戲框架搭建 2017 (二十二) 簡易引用計數器
- Unity 游戲框架搭建 2017 (二十三) 重構小工具 Platform
- Unity 游戲框架搭建 2017 (二十四) 小結