10

Unity3D研究院之在发布版本屏蔽Debug.log输出的Log(七十)

 3 years ago
source link: https://www.xuanyusong.com/archives/2782
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Unity3D研究院之在发布版本屏蔽Debug.log输出的Log(七十)

写在前面的话, unity5.3支持了运行时关闭产生的debug.log

Debug.logger.logEnabled = false;

在开发Unity的时候,在输出log的时候大家都会采用Debug.log()的方式来输出Log,但是游戏发布的时候这样的Log是不能关闭的,在用户手机运行产生一堆LOG也不是啥好事,一定要关闭才行、主要是unity官方也没有提供直接关闭的方法。

Debug.Log("雨松MOMO");

既然官方没提供方法,那么我们就得自己想办法。于是我写了一个类把Debug.log包了一层。

using UnityEngine;
using System.Collections;
public class Debuger  {
static public bool EnableLog = false;
static public void Log(object message)
Log(message,null);
static public void Log(object message, Object context)
if(EnableLog)
Debug.Log(message,context);
static public void LogError(object message)
LogError(message,null);
static public void LogError(object message, Object context)
if(EnableLog)
Debug.LogError(message,context);
static public void LogWarning(object message)
LogWarning(message,null);
static public void LogWarning(object message, Object context)
if(EnableLog)
Debug.LogWarning(message,context);

 这样我程序在输出Log的时候,我就不调用Debug.Log()了,我使用我新写的这个类。

void Start ()
Debuger.EnableLog = true;
Debuger.Log("雨松MOMO");

 但是这样问题又来了,因为我如果直接这样写的话,如下图所示,当我输出Log以后,我在Console窗口中双击Log 这时候代码会定位在Debuger这个类的Log方法,这太麻烦了我需要定位在调用Debuger.log()的方法上。

Unity3D研究院之在发布版本屏蔽Debug.log输出的Log(七十) - 雨松MOMO程序研究院 - 1

为了解决这个问题,我们可以把Debuger类做成一个dll,在终端里面输入如下代码 。。

mcs -r:/Applications/Unity/Unity.app/Contents/Frameworks/Managed/UnityEngine.dll -target:library ClassesForDLL.cs

 如果你要把多个.cs文件做成一个dll的话,那么在终端里用空格把你的.cs文件分开即可,于是我在终端里面输入,参数 就是我的cs的完整路径。

mcs -r:/Applications/Unity/Unity.app/Contents/Frameworks/Managed/UnityEngine.dll -target:library /Users/MOMO/test13/Assets/Debuger.cs

执行完毕后,会自动的在你脚本的平级路径下生成一个同名的dll文件。 在把Debuger.cs文件删除,保留Debuger.dll就可以了。

如果你的版本正式发布, 你只需找一个合适的地方调用enableLog = true就可以。

Debuger.EnableLog = true;

开始我想的是在Debuger类里面直接用 #if define这样的标签来做,后来我发现很多问题出现在正式版本里,一旦使用预定义标签编译那么除非重新打包不然是觉对看不到LOG。所以干脆就直接用一个静态变量来标记是否打开Log方便。这样可以让服务端做一个密令一类的东西, 正式版也能让客户端把LOG打开。。

如果你确定你的项目不会出问题,不需要运行时产生log.那么最好使用Conditional, 参数就是条件编译的预定义标签,下面的DEBUG 就是在unity projectsetting 里面 声明 预定义标签, 当然你也可以自己去定义这些标签。这样在调用方法的时候就不会去执行 方法体的内容。。 

需要引入头文件

using System.Diagnostics;
using System;

[Conditional ("DEBUG")]
static public void Log(object message, Object context)
Debug.Log(message,context);

最后我把这个简单的DLL上传一下,大家下载下来就可以直接用了。。或者你也可以按照本文的方法自己来封装。

下载地址: http://pan.baidu.com/s/1ntyoEF3

作者:雨松MOMO
专注移动互联网,Unity3D游戏开发
捐 赠写博客不易,如果您想请我喝一杯星巴克的话?就进来看吧!

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK