遇到报错会直接显示在页面上,并且会在游戏 .exe 所在的目录,创建 ErrorLog.txt文件
C#
using UnityEngine;
using System.Collections.Generic;
using System.IO; // 文件操作需要引入的命名空间
using System.Collections;
public class ScreenLogger : MonoBehaviour
{
public bool showLog = true;
public int maxLines = 30; // 屏幕最多显示多少行
public int fontSize = 24; // 字体大小
private List<string> logList = new List<string>();
private string logText = "";
private GUIStyle logStyle;
// 自定义日志文件的路径(放在游戏exe旁边)
private string errorLogPath;
void Start()
{
// 获取游戏 exe 所在的目录,并在其下创建 ErrorLog.txt
// Application.dataPath 在打包后指向的是 "游戏名_Data" 文件夹,所以要用 Directory.GetParent 往上退一层
DirectoryInfo dataDir = new DirectoryInfo(Application.dataPath);
string gameRootDir = dataDir.Parent.FullName;
errorLogPath = Path.Combine(gameRootDir, "ErrorLog.txt");
// 每次启动游戏时,清空之前的报错日志(也可以改成追加,看需求)
File.WriteAllText(errorLogPath, "=== 游戏启动,开始记录错误日志 ===\n");
}
void OnEnable()
{
Application.logMessageReceived += HandleLog;
}
void OnDisable()
{
Application.logMessageReceived -= HandleLog;
}
void HandleLog(string logString, string stackTrace, LogType type)
{
// 只处理警告和报错
if (type == LogType.Error || type == LogType.Exception || type == LogType.Warning)
{
// 1. 处理屏幕显示
string color = (type == LogType.Error || type == LogType.Exception) ? "red" : "yellow";
string newLog = $"<color={color}>[{type}] {logString}\n{stackTrace}</color>\n";
logList.Add(newLog);
if (logList.Count > maxLines) logList.RemoveAt(0);
logText = string.Join("", logList);
// 2. 处理文件写入 (写入到 ErrorLog.txt)
string fileLog = $"[{System.DateTime.Now:HH:mm:ss}] [{type}] {logString}\n堆栈追踪:\n{stackTrace}\n" +
"--------------------------------------------------------\n";
// 追加写入文件
File.AppendAllText(errorLogPath, fileLog);
}
}
void OnGUI()
{
if (!showLog || string.IsNullOrEmpty(logText)) return;
if (logStyle == null)
{
logStyle = new GUIStyle(GUI.skin.label);
logStyle.fontSize = fontSize;
logStyle.richText = true;
logStyle.alignment = TextAnchor.UpperLeft;
logStyle.wordWrap = true;
}
GUI.backgroundColor = new Color(0, 0, 0, 0.8f);
GUI.Box(new Rect(10, 10, Screen.width - 20, Screen.height / 2), "");
GUI.backgroundColor = Color.clear;
GUI.Label(new Rect(15, 15, Screen.width - 30, Screen.height / 2 - 10), logText, logStyle);
}
}