Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

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("
");
        }

        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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...