lcy
3 天以前 2dd1841d03a730d3d369092c2a3ad656cee4bf64
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
48
49
50
51
52
53
54
55
using UnityEngine;
 
 
public static class BattleDebug
{
#if UNITY_EDITOR
    // 每次 Editor 进入 PlayMode 会重置这个 static,初次调用时清空旧文件
    private static bool _logFileInitialized = false;
    private static string _logFilePath;
 
    private static void EnsureLogFile()
    {
        if (_logFileInitialized) return;
        _logFileInitialized = true;
        try
        {
            string dir = Application.dataPath + "/../BattleReport";
            if (!System.IO.Directory.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);
            _logFilePath = dir + "/BattleDebug.log";
            // 每次启动 PlayMode 清空文件,避免跨次污染
            System.IO.File.WriteAllText(_logFilePath, $"=== BattleDebug log opened at {System.DateTime.Now:HH:mm:ss.fff} ===\n");
        }
        catch (System.Exception e)
        {
            Debug.LogWarning("BattleDebug 打开日志文件失败:" + e.Message);
            _logFilePath = null;
        }
    }
 
    private static void WriteToFile(string line)
    {
        EnsureLogFile();
        if (string.IsNullOrEmpty(_logFilePath)) return;
        try
        {
            System.IO.File.AppendAllText(_logFilePath,
                $"[{Time.frameCount} {Time.realtimeSinceStartup:F3}] " + line + "\n");
        }
        catch { /* 忽略文件写入异常,别影响逻辑 */ }
    }
#endif
 
    public static void LogError(string _logMessage)
    {
#if UNITY_EDITOR
        if (Launch.Instance != null && Launch.Instance.isOpenBattleDebug)
        {
            Debug.LogWarning("BattleLog: " + _logMessage);
            if (Launch.Instance.isOpenBattleDebugLogFile)
                WriteToFile(_logMessage);
        }
#endif
    }
}