为毛要实现这个工具?

  1. 在我小时候,每当游戏在真机运行时,我们看到的日志是这样的。

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

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

如何使用?

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

QConsole.Instance();
复制代码

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

在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_EDITORif (Input.GetKeyUp(KeyCode.F1))this.showGUI = !this.showGUI;#elif UNITY_ANDROIDif (Input.GetKeyUp(KeyCode.Escape))this.showGUI = !this.showGUI;#elif UNITY_IOSif (!mTouching && Input.touchCount == 4){mTouching = true;this.showGUI = !this.showGUI;} else if (Input.touchCount == 0){mTouching = false;}#endifif (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_EDITOREditorApplication.isPlaying = false;#elseApplication.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 entryfor (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 itif (collapse && i > 0 && entry.message == entries[i - 1].message) {continue;}// Change the text colour according to the log typeswitch (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 buttonif (GUILayout.Button(clearLabel)) {entries.Clear();}// Collapse togglecollapse = 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 barGUI.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。

欢迎讨论!

相关链接:

我的框架地址:https://github.com/liangxiegame/QFramework

教程源码:https://github.com/liangxiegame/QFramework/tree/master/Assets/HowToWriteUnityGameFramework/

QFramework&游戏框架搭建QQ交流群: 623597263

转载请注明地址:凉鞋的笔记http://liangxiegame.com/

微信公众号:liangxiegame

如果有帮助到您:

如果觉得本篇教程对您有帮助,不妨通过以下方式赞助笔者一下,鼓励笔者继续写出更多高质量的教程,也让更多的力量加入 QFramework 。

  • 购买 gitchat 话题《Unity 游戏框架搭建:资源管理 与 ResKit 精讲》

    • 价格: 6 元,会员免费
    • 地址: http://gitbook.cn/gitchat/activity/5b29df073104f252297a779c
  • 给 QFramework 一个 Star
    • 地址: https://github.com/liangxiegame/QFramework
  • 给 Asset Store 上的 QFramework 并给个五星(需要先下载)
    • 地址: http://u3d.as/SJ9
  • 购买 gitchat 话题《Unity 游戏框架搭建:我所理解的框架》
    • 价格: 6 元,会员免费
    • 地址: http://gitbook.cn/gitchat/activity/5abc3f43bad4f418fb78ab77
  • 购买同名电子书 :https://www.kancloud.cn/liangxiegame/unity_framework_design( 29.9 元,内容会在 2018 年 10 月份完结)

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

  1. Unity 游戏框架搭建 (七) 减少加班利器-QApp类

    本来这周想介绍一些框架中自认为比较好用的小工具的,但是发现很多小工具都依赖一个类----App. App类的职责: 1.接收Unity的生命周期事件. 2.做为游戏的入口. 3.一些框架级别的组件初始 ...

  2. Unity 游戏框架搭建 (二十一) 使用对象池时的一些细节

    上篇文章使用SafeObjectPool实现了一个简单的Msg类.代码如下: class Msg : IPoolAble,IPoolType{#region IPoolAble 实现public vo ...

  3. Unity 游戏框架搭建 (五) 简易消息机制

    什么是消息机制? 23333333,让我先笑一会. 为什么用消息机制? 三个字,解!!!!耦!!!!合!!!!. 我的框架中的消息机制用例: 1.接收者 using UnityEngine;names ...

  4. Unity 游戏框架搭建 2018 (四) 我所理解的框架

    前言 架构和框架这些概念听起来很遥远,让很多初学者不明觉厉.会产生"等自己技术牛逼了再去做架构或者搭建框架"这样的想法.在这里笔者可以很肯定地告诉大家,初学者是完全可以去做这些事情 ...

  5. Unity 游戏框架搭建 2018 (一) 架构、框架与 QFramework 简介

    约定 还记得上版本的第二十四篇的约定嘛?现在出来履行啦~ 为什么要重制? 之前写的专栏都是按照心情写的,在最初的时候笔者什么都不懂,而且文章的发布是按照很随性的一个顺序.结果就是说,大家都看完了,都还 ...

  6. Unity 游戏框架搭建 2019 (四十五) 独立的方法和独立的类

    我们在开始本示例之前,先整理出我们当前库中的代码类型. 工具方法:CommonUtil.GameObjectSimplify等. 类: MonoBehaviourSimplify. 静态方法中的方法全 ...

  7. Unity 游戏框架搭建 2019 (四十二) MonoBehaviour 简化

    在前两篇,我们完成了第九个示例.为了完善第九个示例,我们复习了类的继承,又学习了泛型和 params 关键字. 我们已经接触了类的继承了.接触继承之前,把类仅仅当做是方法的集合,接触了继承之后,我们的 ...

  8. Unity 游戏框架搭建 2019 (四十七) 集成到 MonoBehaviourSimplify

    还记得我们的简易消息机制是为了解决什么问题诞生的嘛? 是为了解决脚本间访问的问题. 我们回过头再看下 A 脚本如果想访问 B 脚本,使用消息机制,如何实现. 代码如下: public class A ...

  9. unity游戏框架学习-框架结构

    转眼毕业三年了,算上实习差不多四年的游戏开发了,一直想自己鼓捣套框架,奈何能力太次,不知道从哪开始.但是万事开头难,总要踏出第一步,才会有后面的两步,三步- 我认为的unity游戏框架就是一整套的工具 ...

最新文章

  1. 2022-2028年中国文化创意产业园区域发展模式与产业整体规划研究报告
  2. Makefile 学习 2 - 基于若干 Blog 的汇总
  3. 大工17春计算机文化基础,大工17春《计算机文化基础》在线测试
  4. matlab画二维颜色深浅,matlab中如何为二维图形填充渐进的颜色
  5. DOS批处理高级教程精选(二)
  6. Maven问题-maven projects dependencies标红,但jar包事实上是没问题的
  7. 钉钉机器人自动回复消息_如何利用闲鱼助手,真正实现全自动消息回复,做到效率最大化...
  8. Java 代理模式之三:Cglib动态代理
  9. 8月5日发布卡巴斯基授权许可key-卡巴斯基key
  10. java企业绩效_员工绩效管理系统,基于SSM框架下的JAVA系统
  11. Oracle客户端使用
  12. 51单片机系列--8位数码管
  13. 淘宝价格带卡位公式是什么?如何定价?
  14. 自己写的uvc摄像头驱动程序
  15. python制作工资表_Python实用案例:一秒自动生成工资条。
  16. RuiJi Scraper 分页抽取
  17. Java实现找回密码
  18. AG256SL100 与EPM240T100 完全PIN TO PIN兼容
  19. list.stream distinct列表去重
  20. 都23年了你还记得渐进式框架是什么意思吗

热门文章

  1. 生鲜配送小程序源码_生鲜社区团购配送系统小程序源码搭建平台模式
  2. html自动滑动轮播代码,html+css+js 实现自动滑动轮播图
  3. java%4d_java积累
  4. python1.学生管理系统
  5. Java线程中关于Synchronized的用法
  6. 2021前端高频面试题整理,附答案
  7. mongodb数组字段prefix匹配返回
  8. Linux下java -version版本不对
  9. linux进程通讯-纯文本文件
  10. matlab拟合四次函数表达式,用matlab编写程序求以幂函数作基函数的3次、4次多项式的最小二乘曲线拟合,画出数据散点图及拟合曲线图...