Unity3D Debug写入Txt

核心代码:

        public static event LogCallback logMessageReceivedThreaded;
        public static event LogCallback logMessageReceived;

------------------------------------------------------------------------------------------

public delegate void LogCallback(string condition, string stackTrace, LogType type);

完整代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class Logger : MonoBehaviour
{
    private string outPath;
    private void Start()
    {
        InitLogger();

        Debug.Log("11111111111111111111111");
        Debug.LogWarning("22222222222222222222222");
        Debug.LogError("33333333333333333333333");

    }

    private void OnEnable()
    {
        Application.logMessageReceivedThreaded += LogCallBack;
    }

    private void OnDisable()
    {
        Application.logMessageReceivedThreaded -= LogCallBack;
    }
    public void InitLogger()
    {
        outPath = Application.dataPath + "/outLog.txt";

        if (File.Exists(outPath))
        {
            File.Delete(outPath);

        }

        Debug.Log(outPath.Replace("/outLog.txt", ""));

        if (Directory.Exists(Application.dataPath))
        {
            FileStream fs = File.Create(outPath);
            fs.Close();

            Debug.Log("注册回调");

        }
        else
        {
            Debug.LogError("文件不存在");
        }
    }

    private void LogCallBack(string condition, string stackTrace, LogType type)
    {
        Debug.Log("回调执行");
        if (File.Exists(outPath))
        {
            using (StreamWriter sw = File.AppendText(outPath))
            {
                sw.WriteLine(condition);
                sw.WriteLine(stackTrace);

            }
        }
    }
}

上一篇:解决Unity3D使用VRTK时,VR眼镜连接不上的问题


下一篇:【Unity3D 灵巧小知识点】 ☀️ | Unity中几个简单又常见的报错异常