Unity中写文件到本地

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZFSR05255134/article/details/62226014

环境:unity5.3,C#

目的:将信息写入到本地文件,方便查看。

using UnityEngine;
//using System.Collections;
using System.IO;

/// <summary>
/// 写文件
/// </summary>
public class WriteLog
{
    private string m_infoFile;

    private static readonly object s_lock = new object();
    private static WriteLog s_instance;
    public static WriteLog instance
    {
        get
        {
            if (s_instance == null)
            {
                lock (s_lock)
                {
                    if (s_instance == null)
                    {
                        s_instance = new WriteLog();
                    }
                }
            }
            return s_instance;
        }
    }

    private WriteLog()
    {
        Init();
    }

    private void Init()
    {
#if UNITY_EDITOR
        string dir = Application.dataPath;
        int index = dir.LastIndexOf("/");
        dir = dir.Substring(0, index);
        dir += "/GameLog";
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        m_infoFile = dir + "/" + "gamelog.txt";
#else
        string dir = string.Format("{0}/{1}", Application.persistentDataPath, "GameLog");
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        m_infoFile = dir + "/" + "gamelog.txt";
#endif
    }

    /// <summary>
    /// 获取调用堆栈信息
    /// </summary>
    private string GetStackTrace()
    {
        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true);
        string stackIndent = "";
        for (int i = 0; i < st.FrameCount; i++)
        {
            System.Diagnostics.StackFrame sf = st.GetFrame(i);

            //得到错误的方法
            stackIndent += sf.GetMethod() + "";
            //得到错误的文件名
            stackIndent += sf.GetFileName() + "";
            //得到文件错误的行号
            stackIndent += (":" + sf.GetFileLineNumber()) + "";
            ////得到错误的列
            //stackIndent += " column:" + sf.GetFileColumnNumber() + " ";

            stackIndent += "\n";
        }
        return stackIndent;
    }

    /// <summary>
    /// 写入信息到本地文件
    /// </summary>
    /// <param name="info">信息</param>
    public void WriteInfo(string info)
    {
        using (StreamWriter sw = File.AppendText(m_infoFile))
        {
            //string stackInfo = new System.Diagnostics.StackTrace().ToString();
            string stackInfo = GetStackTrace();
            info += ("\n" + stackInfo);
            sw.WriteLine(info);
        }
    }
}


猜你喜欢

转载自blog.csdn.net/ZFSR05255134/article/details/62226014
今日推荐