分享一篇输出Unity Log到文本的脚本。
在手机上调试看Log相当方便,不用写一堆OnGUI做显示,OnGUI还容易写错出问题。
/*
* By: Fox.Huang 黄文叶, Date:2018.12.18
*/
using UnityEngine;
using System.IO;
public class DebugLogOutput
{
static bool s_HasInit = false;
static string s_LogPath = null;
static int s_LastCount = 0; // 这个变量相关的逻辑,是用来做重新信息处理的.因为有时候错误会噼里啪啦的跳,减缓一点IO压力.
static string s_LastLog = "";
public static void InitLogFile(string logPath)
{
if (!string.IsNullOrEmpty(logPath))
{
s_HasInit = true;
s_LogPath = logPath;
}
}
public static void HandleLog(string logString, string stackTrace, LogType type)
{
if (s_HasInit)
{
string logContent = "[" + type.ToString() + "]" + logString;
if (s_LastCount < 10 || s_LastLog != logContent)
{
if (s_LastLog == logContent)
{
++s_LastCount;
}
else
{
s_LastCount = 1;
s_LastLog = logContent;
}
using (StreamWriter sw = new StreamWriter(s_LogPath, true, System.Text.Encoding.GetEncoding("UTF-8")))
{
sw.WriteLine(logContent);
sw.Close();
}
}
}
}
}
然后是使用的部分
DebugLogOutput.InitLogFile(Application.persistentDataPath + "/Log.txt");// 初始化需要输出的路径
Application.logMessageReceived += DebugLogOutput.HandleLog;//添加监听
Application.logMessageReceived -= DebugLogOutput.HandleLog;//移除监听
程序学无止尽。
欢迎大家沟通,有啥不明确的,或者不对的,也可以和我私聊
我的QQ 334524067 神一般的狄狄