1 回答
TA贡献1794条经验 获得超8个赞
LogCallback
您可以使用一个类并添加带有签名的回调方法Application.logMessageReceived
和/或Application.logMessageReceivedThreaded
并使用初始化类[RuntimeInitializeOnLoadMethod]
例如,用于在运行时收集所有日志输出
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;
}
}
当然,您不仅可以将它们收集在列表中,HandleLog
还可以使用接收到的日志数据,例如将其添加到组件UI.Text
等
或者,直接显示文本的最简单解决方案也是使用之前的方法,但在 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 关注
- 97 浏览
添加回答
举报