1 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
LogCallback
您可以使用一個(gè)類并添加帶有簽名的回調(diào)方法Application.logMessageReceived
和/或Application.logMessageReceivedThreaded
并使用初始化類[RuntimeInitializeOnLoadMethod]
例如,用于在運(yùn)行時(shí)收集所有日志輸出
public static class DebugListener
{
? ? public static List<LogEntry> logs = new List<LogEntry>();
? ? [RuntimeInitializeOnLoadMethod]
? ? private static void InitializeOnLoad()
? ? {
? ? ? ? // removing the callback first makes sure it is only added once
? ? ? ? Application.logMessageReceived -= HandleLog;
? ? ? ? Application.logMessageReceived += HandleLog;
? ? }
? ? private static void HandleLog(string logString, string stackTrace, LogType type)
? ? {
? ? ? ? logs.Add(new LogEntry(logString, stackTrace, type));
? ? }
}
[Serializable]
public class LogEntry
{
? ? public string Message;
? ? public string StackTrace;
? ? public LogType Type;
? ? // default constructor is required for serialization
? ? public LogEntry() { }
? ? public LogEntry(string message, string stackTrace, LogType type)
? ? {
? ? ? ? Message = message;
? ? ? ? StackTrace = stackTrace;
? ? ? ? Type = type;
? ? }
}
當(dāng)然,您不僅可以將它們收集在列表中,HandleLog
還可以使用接收到的日志數(shù)據(jù),例如將其添加到組件UI.Text
等
或者,直接顯示文本的最簡(jiǎn)單解決方案也是使用之前的方法,但在 MonoBehaviour 組件中,并使用和顯示OnGUI
文本GUI.Label
public class DebugListener : MonoBehaviour
{
? ? private string lastMessage;
? ? private string lastStackTrace;
? ? private LogType lastType;
? ? private void OnEnable()
? ? {
? ? ? ? Application.logMessageReceived += HandleLog;
? ? }
? ? private void OnDisable()
? ? {
? ? ? ? Application.logMessageReceived -= HandleLog;
? ? }
? ? private void HandleLog(string message, string stack, LogType type)
? ? {
? ? ? ? lastMessage = message;
? ? ? ? lastStackTrace = stack;
? ? ? ? lastType = type;
? ? }
? ? private void OnGUI()
? ? {
? ? ? ? if(string.IsNullOrEmpty(lastMessage)) return;
? ? ? ? // show text at certain offset from left top corner
? ? ? ? // and certain size
? ? ? ? // e.g. simply place it in the center of the screen?
? ? ? ? // and make it overlay the entire screen
? ? ? ? GUI.Label(new Rect(Screen.width / 2f, Screen.height / 2f, Screen.width, Screen.height), $"{lastType}\n{lastMessage}\n{lastStackTrace}");
? ? }
}
- 1 回答
- 0 關(guān)注
- 128 瀏覽
添加回答
舉報(bào)