Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting Debug.log as a GUI element in unity

My program currently displays text in the console.

I want this text to be displayed in the game window.

The data is part of a web request.

Is there a simple way of displaying what appears in the console as a GUI element?

like image 757
okmijn Avatar asked Feb 09 '26 22:02

okmijn


1 Answers

Yes you can simply add a callback to e.g. Application.logMessageReceivedThreaded

Example from the API extended with OnGUI script from this thread

// 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
        );
    }
}

In general: OnGUI is kind of legacy and you should really only use this for debugging.

But you can basically use the same script also for e.g. a UI.Text component and instead of using OnGUI assign the text to it.

The script would basically look the same but have a

public Text text;

and instead of OnGUI would directly do

text.text = builder.ToString();
like image 156
derHugo Avatar answered Feb 16 '26 20:02

derHugo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!