Unity Debug.Log 性能分析

1.介绍

介绍Debug.Log , 主要是因为发现有些同学,对这个并不是很在意,可能以为只是打印到Unity控制台。当你发Release版本的时候,Unity并不会自动帮你禁用Debug.Log,Debug.Log会产生GC,非常影响性能(开启Unity Deep Profiler可以查看性能分析)。

Unity5.3提供手动关闭Debug功能

if (Debug.isDebugBuild) {
    Debug.logger.logEnabled = true;
    //Debug.logger.filterLogType = LogType.Log; //显示所有
} else {
    Debug.logger.logEnabled = false;
    //Debug.logger.filterLogType = LogType.Error;//只显示Error + Exception
}

(这样虽然关闭Log输出, 但是需要开发者主动避免会产生GC的参数传递)
例如 Debug.Log(“Hello”+”World”);

2.Conditional

不过最好采用条件编译标签Conditional封装一层自己的Log输出,来直接避免掉Log输出的编译,还可以省去Log函数参数传递和调用的开销。

//伪代码
public static class DebugEx {
     //需要在Unity PlayerSettings -> Scripting Define Symbol 添加VERBOSE
     //Release发布时去掉VERBOSE,所有的DebugEx.Log函数调用将不会参与编译。
     //这是简单的实现方式 , 后期功能的扩展以及Debug和Release自动切换机制,可以开发者进行封装。
     [Conditional("VERBOSE")] 
     public static void Log(object message, UnityEngine.Object obj = null) {
         UnityEngine.Debug.Log(message, obj);
     }

     public static void LogWarning(object message, UnityEngine.Object obj = null) {
         UnityEngine.Debug.LogWarning(message, obj);
     }

     public static void LogError(object message, UnityEngine.Object obj = null) {
         UnityEngine.Debug.LogError(message, obj);
     }
 }

3.Log插件

Log Viewer 非常好的Log免费插件 5星推荐!
Unity Assets Store下载地址

猜你喜欢

转载自blog.csdn.net/lile1234_show/article/details/81389692