BITKit/Src/Unity/Scripts/UX/Debuger/UXDebuger.cs

68 lines
2.0 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BITKit;
using UnityEngine.UIElements;
using Cysharp.Threading.Tasks;
using System.Linq;
using System.Net.Http;
using System.Text;
using UnityEngine.Serialization;
namespace BITKit.UX
{
public sealed class UXDebuger : MonoBehaviour
{
[SerializeField] private Color textColor = Color.black;
[SerializeField]private GUIStyle style;
[SerializeReference, SubclassSelector] private IReference postApi;
[SerializeField] private bool hidePostLog;
private readonly StringBuilder _logBuilder=new();
private readonly HttpClient _httpClient = new();
private void OnEnable()
{
Application.logMessageReceivedThreaded += OnLog;
}
private void OnDisable()
{
Application.logMessageReceivedThreaded -= OnLog;
}
private void OnLog(string condition, string stacktrace, LogType type)
{
_logBuilder.AppendLine(condition);
if (type is LogType.Error or LogType.Exception)
{
_logBuilder.AppendLine(stacktrace);
}
if (string.IsNullOrEmpty(postApi?.Value) is false)
{
try
{
_httpClient.PostAsync(postApi.Value, new StringContent(_logBuilder.ToString())).AsUniTask()
.Forget();
}
catch (Exception)
{
if (hidePostLog) return;
throw;
}
}
}
private void OnGUI()
{
GUILayout.BeginArea(new Rect(120, 120, Screen.width, Screen.height));
GUILayout.BeginVertical();
//颜色更改为黑色
GUI.color = textColor;
GUILayout.Label(string.Join("\n",_logBuilder.ToString().Split("\n").Reverse()),style);
GUILayout.EndVertical();
GUILayout.EndArea();
}
}
}