c# - 统一将 Debug.log 作为 GUI 元素

标签 c# unity3d

我的程序当前在控制台中显示文本。

我希望在游戏窗口中显示此文本。

数据是网络请求的一部分。

是否有一种简单的方法可以将出现在控制台中的内容显示为 GUI 元素?

最佳答案

是的,您可以简单地添加一个回调,例如Application.logMessageReceivedThreaded

使用来自 this threadOnGUI 脚本扩展的 API 示例

// Put this on any GameObject in the scene
public class ExampleClass : MonoBehaviour
{
    // Adjust via the Inspector
    public int maxLines = 8;
    private Queue<string> queue = new Queue<string>();
    private string currentText = "";

    void OnEnable()
    {
        Application.logMessageReceivedThreaded += HandleLog;
    }

    void OnDisable()
    {
        Application.logMessageReceivedThreaded -= HandleLog;
    }

    void HandleLog(string logString, string stackTrace, LogType type)
    {
        // Delete oldest message
        if (queue.Count >= maxLines) queue.Dequeue();

        queue.Enqueue(logString);

        var builder = new StringBuilder();
        foreach (string st in queue)
        {
            builder.Append(st).Append("\n");
        }

        currentText = builder.ToString();
    }

    void OnGUI()
    {
        GUI.Label(
           new Rect(
               5,                   // x, left offset
               Screen.height - 150, // y, bottom offset
               300f,                // width
               150f                 // height
           ),      
           currentText,             // the display text
           GUI.skin.textArea        // use a multi-line text area
        );
    }
}

总的来说:OnGUI 是一种遗留物,您真的应该只将它用于调试。

但是您基本上也可以使用相同的脚本,例如一个UI.Text组件,而不是使用 OnGUI 将文本分配给它。

脚本基本上看起来是一样的但是有一个

public Text text;

而不是 OnGUI 会直接做

text.text = builder.ToString();

关于c# - 统一将 Debug.log 作为 GUI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60228993/

相关文章:

c# - 在表值参数中将 nvarchar 长度设置为最大值

c# - 在服务器和客户端之间发送查询结果的最有效方式是什么

c# - Unity汽车自行转向

c# - 为什么 C# 使用 [System.Serializable] 来保存实例? (Unity3D)

c# - Unity 通过网络发送和接收麦克风音频

ios - Unity 5.1.1错误: dll is not allowed to be included or could not be found

c# - 如何从 Windowsphone 的 shoutcast 广播 channel 获取元数据?

c# - 如何查看应用程序在客户端计算机上运行时的异常?

c# - 在 C# 中格式化大数

c# - 是否可以将值绑定(bind)到文件 "App Settings"直接到 css 样式表中?