Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Getting text from .txt File

Discussion in 'UGUI & TextMesh Pro' started by ATLAS-INTERACTIVE, Mar 21, 2015.

  1. ATLAS-INTERACTIVE

    ATLAS-INTERACTIVE

    Joined:
    Mar 3, 2014
    Posts:
    1,421
    Not sure whether to put this in Scripting or here, but is it possible to get text from a text file and place it in a UI Text component?
    This is for a book system and I don't think I would be able to do this any other way.
     
  2. Feaver1968

    Feaver1968

    Joined:
    Nov 16, 2014
    Posts:
    70
    You can use Resources.Load to load TextAssets from within your project. They need to be .txt files in a Resources folder of your project.
    Another option is to use the C# way of reading files, there are a few ways to do that.
    As far as the Text component though, there is a hard limit on how many characters you can load into a canvas. I only mention because if you are not careful loading a books worth of text into Text.text you'll probably get an error.
     
    SimonDarksideJ likes this.
  3. mantekkerz

    mantekkerz

    Joined:
    Dec 24, 2013
    Posts:
    111
    As above. In my project I use a mix of Unity's TextAsset which is easily read by one line of a code- this for the type of text files that will be bundled with the game and so not edited by the end user. For other files that the end user will edit, i.e. located outside the project, I use the C# StreamReader. It's also really easy to use, just a few lines to read a external file.

    As for the text limit, I'm not sure what it is. But I would probably create a empty Text UI GO with a Layout Element component and make it a prefab. Read your text, split it up into smaller chunks then just instantiate prefabs in a loop, filling it with chunks as it goes. Then slap a Layout component onto it's containing panel to keep things looking good.
     
  4. ATLAS-INTERACTIVE

    ATLAS-INTERACTIVE

    Joined:
    Mar 3, 2014
    Posts:
    1,421
    This all worked, after reading a bit on TextAssets, this worked very well, thanks.