捕获程序异常并输出Log到屏幕上

将该脚本挂到场景中任意的GameObjec上,这样在移动端上就可以显示Log信息,并捕获程序异常

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

public class ULog : MonoBehaviour
{
    static List<string> mLines = new List<string>();
    static List<string> mWriteTxt = new List<string>();
    private string outpath;
    /// 
    /// 是否输出日志到界面上
    /// 
    public bool isOutputScreen = true;
    /// 
    /// 是否记录日志
    /// 
    static public bool IsDebug = true;
    //------------------scroll view--------------
    public Vector2 scrollPosition = Vector2.zero;
    public float scrollVelocity = 0f;
    public float timeTouchPhaseEnded = 0f;
    public float inertiaDuration = 0.5f;
    public Vector2 lastDeltaPos;
    //-------------------------------------------
    void Start()
    {
        //Application.persistentDataPath Unity中只有这个路径是既可以读也可以写的。
        if (Application.platform == RuntimePlatform.WindowsEditor)
        {
            outpath = Application.dataPath + "/UnityLog.txt";
        }
        else//android
        {
            outpath = Application.persistentDataPath + "/UnityLog.txt";
        }
        //每次启动客户端删除之前保存的Log
        if (System.IO.File.Exists(outpath))
        {
            File.Delete(outpath);
        }
        //在这里做一个Log的监听
        Application.logMessageReceived += HandleLog;
    }

    /// 
    /// Log写入文件
    /// 
    void Update()
    {
        if (IsDebug)
        {
            //因为写入文件的操作必须在主线程中完成,所以在Update中哦给你写入文件。
            if (mWriteTxt.Count > 0)
            {
                string[] temp = mWriteTxt.ToArray();
                foreach (string t in temp)
                {
                    using (StreamWriter writer = new StreamWriter(outpath, true, Encoding.UTF8))
                    {
                        writer.WriteLine(t);
                    }
                    mWriteTxt.Remove(t);
                }
            }

            if (Input.touchCount > 0)
            {
                if (Input.GetTouch(0).phase == TouchPhase.Moved)
                {
                    scrollPosition.y += Input.GetTouch(0).deltaPosition.y * 5;
                    lastDeltaPos = Input.GetTouch(0).deltaPosition;
                }
                else if (Input.GetTouch(0).phase == TouchPhase.Ended)
                {
                    if (Mathf.Abs(lastDeltaPos.y) > 5.0f)
                    {
                        scrollVelocity = (int)(lastDeltaPos.y * 0.5 / Input.GetTouch(0).deltaTime);
                        //print(scrollVelocity);
                    }
                    timeTouchPhaseEnded = Time.time;
                }
            }
            else
            {
                if (scrollVelocity != 0.0f)
                {
                    // slow down
                    float t = (Time.time - timeTouchPhaseEnded) / inertiaDuration;
                    float frameVelocity = Mathf.Lerp(scrollVelocity, 0, t);
                    scrollPosition.y += frameVelocity * Time.deltaTime;

                    //if (t >= inertiaDuration)
                    //    scrollVelocity = 0;
                }
            }
        }
    }
    /// 
    /// Log侦听器
    /// 
    ///
    void HandleLog(string logString, string stackTrace, LogType type)
    {
        if (IsDebug && !string.IsNullOrEmpty(logString))
        {
            if (type == LogType.Error || type == LogType.Exception || type == LogType.Log)
            {
                if (mLines.Count > 30)
                {
                    mLines.RemoveAt(0);
                }
                string log = string.Format("{0} {1} {2}: {3}\n{4}", type.ToString(), DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), logString, stackTrace);
                mWriteTxt.Add(log);
                mLines.Add(log);
            }
        }
    }

    void OnGUI()
    {
        if (IsDebug)
        {
            if (isOutputScreen)
            {
                scrollPosition = GUI.BeginScrollView(new Rect(0, 0, 800, Screen.height), scrollPosition, new Rect(0, 0, 790, 2000), false, true);
                GUIStyle style = new GUIStyle();
                style.fontSize = 25;
                style.normal.textColor = Color.green;
                style.wordWrap = true;
                style.fixedWidth = 800;
                for (int i = 0, imax = mLines.Count; i < imax; ++i)
                {
                    GUILayout.Label(mLines[i], style);
                }
                GUI.EndScrollView();
            }

            if (GUI.Button(new Rect(0, 0, 100, 100), "Show"))
            {
                if (isOutputScreen)
                {
                    isOutputScreen = false;
                }
                else
                {
                    isOutputScreen = true;
                }
            }
        }
    }
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值