封装Debug.Log 游戏发布关闭 Log 减少性能消耗

来源:互联网 发布:php sql注入 编辑:程序博客网 时间:2024/06/09 16:43

在游戏发布时,有很多东西需要进行优化 ,消耗性能的东西 能减少就减少。

UnityEngine.Debug.Log 是很消耗性能的操作,即使我们选择的是Release 版本发布,这个函数仍然会执行并且输出Log ,不仅影响性能,还有可能泄漏隐私。所以我们在发布上线时会关掉Log。

比如下面这段代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
usingUnityEngine;
usingSystem.Collections;
 
publicclassNewBehaviourScript : MonoBehaviour {
 
// Use this for initialization
voidStart () {
}
 
voidOnGUI()
{
if(GUILayout.Button("Log"))
{
Debug.Log("test Log");
Debug.LogWarning("test LogWarning");
Debug.LogError("test LogError");
}
}
 
// Update is called once per frame
voidUpdate () {
 
}
}

运行之后在界面上会有 一个按钮 ,点击之后会输出 Log 。

我们打开 Profiler 来监测 CPU的消耗。

可以看到 在点击按钮时,CPU 出现了一个小 波峰。 FPS从1000 掉到了 250 。

点击该波峰,定位到 对应的函数 ,可以看到 输出Log 占用了 84.8% 的CPU(当前)。

赶紧把它干掉吧。

我们来封装一个 LOG,编译成DLL,可以自己控制是否输出Log。

首先用MonoDevelop 新建一个 Library 项目。

右键References , 引用 UnityEngine.dll 。

右键 SNKDebug项目,点击Option 打开设置界面,设置.Net 为 2.0 。

[

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**************************
* 文件名:SNKDebuger.cs;
* 文件描述:Unity Log的封装;
***************************/
 
usingUnityEngine;
usingSystem.Collections;
 
publicclassSNKDebuger  {
 
staticpublicbool EnableLog = true;
staticpublicvoid Log(objectmessage)
{
Log(message,null);
}
staticpublicvoid Log(objectmessage, Object context)
{
if(EnableLog)
{
Debug.Log(message,context);
}
}
staticpublicvoid LogError(objectmessage)
{
LogError(message,null);
}
staticpublicvoid LogError(objectmessage, Object context)
{
if(EnableLog)
{
Debug.LogError(message,context);
}
}
staticpublicvoid LogWarning(objectmessage)
{
LogWarning(message,null);
}
staticpublicvoid LogWarning(objectmessage, Object context)
{
if(EnableLog)
{
Debug.LogWarning(message,context);
}
}
}
 
[

把解决方案配置修改为  Release , 然后点击菜单栏 Build – Build ALL

找到生成的 SNKDebug.dll ,拖到Unity 中,然后像下面使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
usingUnityEngine;
usingSystem.Collections;
 
publicclassNewBehaviourScript : MonoBehaviour {
 
// Use this for initialization
voidStart () {
 
//SNKDebuger.EnableLog = false;
 
}
 
voidOnGUI()
{
if(GUILayout.Button("Log"))
{
SNKDebuger.Log("test Log");
SNKDebuger.LogWarning("test LogWarning");
SNKDebuger.LogError("test LogError");
}
}
 
// Update is called once per frame
voidUpdate () {
 
}
}

如果需要关闭Log ,只需要设置

?
1
SNKDebuger.EnableLog = false;
原创粉丝点击