How to display text from txt file in UI?

Need help
What needs to be fixed in the script to display all the text from the txt file
Currently only one line is displayed
If viewed through the console, then all the text is displayed using:

Console.WriteLine("{0}:{1}",counter,Line);

I would be glad for any help.

using UnityEngine;
using System.IO;
using TMPro;

public class TextUI : MonoBehaviour
{
    public TextMeshProUGUI TextMP;
    void Start()
    {
        StreamReader sr = new StreamReader(@"C:\Users\Professional\Dropbox\SD\text.txt");

        string line = "";
        int counter = 0;

        while ((line = sr.ReadLine()) != null)
        {
            counter++;

            TextMP.text = counter + line;
        }

        void Update()
        {

        }
    }
}

You’re replacing the text with every new line instead of appending to it.

Try:

TextMP.text += counter + line + Environment.NewLine;

That should be good enough for now. Ideally you’d build a whole string and set it in one go.

1 Like

Thanks man, I love you, I spent a week solving this problem.

2 Likes