using UnityEngine;
using System.IO;
public class LogToFile : MonoBehaviour
{
private string logFilePath;
void Start()
{
// 设置文件路径,可以根据需要修改
logFilePath = Application.dataPath + "/log.txt";
// 检查文件是否存在,如果不存在,则创建文件
if (!File.Exists(logFilePath))
{
// 创建文件并关闭文件句柄
File.Create(logFilePath).Close();
}
// 注册日志回调
Application.logMessageReceived += LogToFileHandler;
}
void OnDestroy()
{
// 在销毁时取消日志回调
Application.logMessageReceived -= LogToFileHandler;
}
// 日志回调方法
private void LogToFileHandler(string logText, string stackTrace, LogType type)
{
// 写入日志信息到文件
using (StreamWriter writer = new StreamWriter(logFilePath, true))
{
writer.WriteLine("[" + System.DateTime.Now + "] " + type + ": " + logText);
writer.WriteLine(stackTrace);
writer.WriteLine("--------------------------------------------------");
}
}
}