Unity调试相关

1、LOG处理

  将所有LOG信息写入到文件,并设置部分LOG显示到屏幕上,总结成以下脚本,将其挂载在摄像机上即可。

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

public class LogHandler : MonoBehaviour 
{
    //是否打开日志所在文件夹,默认不打开
    public bool openLogDir = false;
    //最多显示多少条日志到屏幕
    public int showLogSize = 3;
    //设置过滤显示到屏幕的关键字,多个关键字用 | 隔开
    public string filterString = "";
    //日志存储路径
    private string logSavePath;
    //存储显示到屏幕上的日志
    private List<string> logList;
    void Start () {
        logList = new List<string>();
        logSavePath = Application.persistentDataPath + "/log";
        if(openLogDir)
        {
            Application.OpenURL (Application.persistentDataPath);
        }
        //将本次日志与上次启动时的日志分离开
        using(StreamWriter writer = new StreamWriter(logSavePath, true, Encoding.UTF8))
        {
            writer.WriteLine("\n\n----------------------------- 日志分隔线 -----------------------------");
            writer.WriteLine("----------------------------- "+ System.DateTime.Now +" -----------------------------");
        }
        //注册日志处理函数
        Application.logMessageReceived += HandleLog;
    }
    
    void HandleLog(string logString, string stackTrace, LogType type)
    {
        //将所有日志写入到日志文件
        using(StreamWriter writer = new StreamWriter(logSavePath, true, Encoding.UTF8))
        {
            writer.WriteLine(logString + "\n\t\t" + type + ": " + stackTrace.Replace("\n","\n\t\t"));
        }
        //设置过滤条件,将指定类型、包含某些字符串的日志保存到屏幕日志窗器中
        bool show = false;
        //置过滤条件:指定类型
        if (type == LogType.Error || type == LogType.Exception || type == LogType.Warning)
        {
            show = true;
        }
        //置过滤条件:包含指定关键字,多个关键字用 | 隔开
        foreach (string str in filterString.Split('|'))
        {
            if(logString.Contains(str))
            {
                show = true;
                break;
            }
        }
        if(show)
        {
            logList.Add (logString);
            if (logList.Count > showLogSize) 
            {
                logList.RemoveAt(0);
            }
        }
    }

    void OnGUI()
    {
        GUI.color = Color.red;
        for (int i = 0; i < logList.Count; ++i)
        {
            GUILayout.Label(logList[i]);
        }
    }
}

 

posted @ 2015-10-10 15:40 轻典 阅读(...) 评论(...) 编辑 收藏