如何将Unity的Debug信息输出到屏幕上显示

有时候使用adb调试要连接电脑太麻烦,所以如果能够直接显示在屏幕上就好了。

其实可以直接使用一个脚本来完成这个操作,之前使用打dll的方式也许还会导致log的丢失情况。
============================

但是这个会带来了问题,太早的log会看不到,所以应该使用一个可以循环显示的列表来完成这个功能,等以后有时间再完成这个部分。

============代码部分===============

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class DebugerView : MonoBehaviour
{

    public Image ContentImg;
    public Text ContentTex;

    public Button OpenCloseBtn;
    public Transform Main;
    public Text VersionTxt;

    private bool isOpen = false;
    private int contentWidth = 0;

    private List<string> msgList = new List<string>();

    public void Init()
    {
        contentWidth = (int)ContentImg.rectTransform.rect.size.x;

        Application.logMessageReceived += GetMsg;
        Main.gameObject.SetActive(false);
    }


    public void OnOpenCloseClick()
    {
        if (!isOpen)
        {
            Main.gameObject.SetActive(true);
            OpenCloseBtn.GetComponent<Text>().text = "close";
            isOpen = true;
        }
        else
        {
            Main.gameObject.SetActive(false);
            OpenCloseBtn.GetComponent<Text>().text = "open";
            isOpen = false;
        }
    }

    private void GetMsg(string msg, string stackTrace, LogType type)
    {
        msgList.Add(msg);
        switch (type)
        {
            case LogType.Warning:
                msg = string.Format("<color=#FDAD00>{0}</color>", msg); 
                break;
            case LogType.Error:
                msg = string.Format("<color=#FF0000>{0}, {1}</color>", msg, stackTrace);
                break;
            default:
                break;
        }
        if (msgList.Count > 200)
        {
            ClearMsgList();
        }
        ContentTex.text += msg + "\n";
        int contentHeight = (int)ContentTex.preferredHeight;
        ContentImg.rectTransform.sizeDelta = new Vector2(contentWidth, contentHeight);
        ContentImg.transform.localPosition = new Vector3(0, 
        ContentImg.rectTransform.sizeDelta.y - 640, 0);
    }

    private void ClearMsgList()
    {
        //移出100条信息,并重新给ContentTex赋值
        ContentTex.text = string.Empty;
        for (int i = 0; i < 100; ++i)
        {
            msgList.RemoveAt(0);
        }
        for (int i = 0; i < msgList.Count; ++i)
        {
            ContentTex.text += msgList[i] + "\n";
        }
    }

}

猜你喜欢

转载自blog.csdn.net/DoyoFish/article/details/83268562