U3D导出到安卓apk的日志打印管理

虽然U3D提供真机调试,但是由于内外网的隔离,使得这个流程比较麻烦和不太靠谱。真机调试的另一个方法是查看游戏运行导出的Log日志(U3D的Application.persistentDataPath路径下),下面是一个常用的log日志类

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


public class OutputLog : MonoBehaviour 
{
    public static OutputLog instance = null;
    private string err;
    private string log;
    private string filePath;
    private bool isDebugMode = false;

    void Awake()
    {
        filePath = Application.persistentDataPath + "/P1_log.txt";
        if (System.IO.File.Exists(filePath))
        {
            File.Delete(filePath);
        }
        instance = this;
        Application.RegisterLogCallback(HandleLog);
        Debug.Log(filePath);
    }

    void OnDestroy()
    {
        instance = null;
        Application.RegisterLogCallback(null);
    }

    private List writeTxt = new List();
    private void HandleLog(string logString, string stackTrace, LogType type)
    {
        if (type == LogType.Error)
        {
            err += "\n";
            err += logString;
            err += "\n";
            err += stackTrace;
            writeTxt.Add("[Err]" + logString);
            writeTxt.Add(stackTrace);
        }
        else
        {
            log += "\n";
            log += logString;
            writeTxt.Add("[log]" + logString);
            writeTxt.Add(stackTrace);
        }
    }

	void Start () 
    {
        GameObject.Find("Cube").AddComponent();
	}
	
	void Update () 
    {
        if (writeTxt.Count <= 0)
        {
            return;
        }
        string[] temp = writeTxt.ToArray();
        writeTxt.Clear();
        using (StreamWriter writer = new StreamWriter(filePath, true, Encoding.UTF8))
        {
            foreach (string t in temp)
            {
                writer.WriteLine(t);
            }
        }
	}
}


你可能感兴趣的:(unity3d)