
时间2026.07版本Unity 6000.3.19f1using System; using System.IO; using System.Text; using System.Threading.Tasks; using UnityEngine; public class DebugExtend { /// summary /// 是否记录日志信息 /// /summary public static bool IsRecordLog true; /// summary /// 打印日志信息 /// /summary /// param namemessage日志内容/param public static async void Log(object message) { Debug.Log(message); await RecordLogInfo(message, DebugLogType.Log); } /// summary /// 打印日志警告信息 /// /summary /// param namemessage日志内容/param public static async void LogWarning(object message) { Debug.LogWarning(message); await RecordLogInfo(message, DebugLogType.Warning); } /// summary /// 打印日志错误信息 /// /summary /// param namemessage日志内容/param public static async void LogError(object message) { Debug.LogError(message); await RecordLogInfo(message, DebugLogType.Error); } /// summary /// 打印日志信息 /// /summary /// param namemessage日志内容/param /// param namelogType打印日志类型/param public static void Log(object message, DebugLogType logType) { switch (logType) { case DebugLogType.Log: Log(message); break; case DebugLogType.Error: LogError(message); break; case DebugLogType.Warning: LogWarning(message); break; } } /// summary /// 记录日志信息 /// /summary /// param namemessage日志内容/param /// param namelogType打印日志类型/param /// returns/returns private static async Task RecordLogInfo(object message, DebugLogType logType) { if (!IsRecordLog) return; // 若关闭日志输出则不再进行记录 if (!Debug.unityLogger.logEnabled) return; string filePath ; string fileName ${logType}.txt; string newLine Environment.NewLine; // 换行符处理保证跨平台兼容性 string time_stamp ${DateTime.Now:yyyy-MM-dd HH:mm:ss}; // 当前时间戳 string appendContent $[{logType.ToString().ToLower()}] {time_stamp}{newLine}{message}{newLine}{newLine}; #if UNITY_EDITOR filePath Path.Combine(Application.dataPath, Editor, fileName); #elif UNITY_ANDROID || UNITY_IOS || UNITY_WEBGL filePath Path.Combine(Application.persistentDataPath, fileName); #else filePath Path.Combine(Environment.CurrentDirectory, fileName); #endif #if UNITY_WEBGL !UNITY_EDITOR File.AppendAllText(filePath, appendContent, Encoding.UTF8); if (File.Exists(filePath)) Debug.Log($Save content\n{File.ReadAllText(filePath)}); await Task.Delay(1); #else Debug.Log(Save file path : filePath); // 确保目录存在 Directory.CreateDirectory(Path.GetDirectoryName(filePath)); // 异步追加文件内容避免主线程卡顿 await Task.Run(() { try { #if !UNITY_ANDROID !UNITY_IOS //// 方法一true表示追加模式 //using (StreamWriter writer new StreamWriter(filePath, true)) //{ // writer.Write(appendContent); //} #endif // 方法二追加文本如果文件不存在会自动创建指定编码格式 File.AppendAllText(filePath, appendContent, Encoding.UTF8); } catch (Exception e) { Debug.LogError($Unable to write log content{e.Message}); } }); #endif #if UNITY_EDITOR // 刷新资源数据刷新日志信息 UnityEditor.AssetDatabase.Refresh(); #endif } } public enum DebugLogType { Log, Warning, Error }