Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Reading from a text file after game is built

Discussion in 'Scripting' started by greglo, Aug 27, 2019.

  1. greglo

    greglo

    Joined:
    Aug 1, 2018
    Posts:
    13
    Hello,

    I want to read numbers [possibly strings in the future] from a text file, preferably .txt format. But I want this to happen only after the game has been built: the numbers will then be loaded into an array at launch.

    In other words, when the game is run from its .exe, it will read the numbers from the file which is in that very same Unity build folder. This way the players can themselves edit the numbers and mod the game. If the file is not read or is empty, I will use my own default internal integer array.

    I'm a big noob at this aspect; I would appreciate a simple method with a thorough explanation. I have looked at Application.streamingAssetsPath and StreamReader but it's all a little alien to me.

    Thanks for your help.
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,294
    Where is this file?

    If it's in the StreamingAssets folder, it's really just:

    Code (csharp):
    1. var text = File.ReadAllText(Application.streamingAssetsPath + "/nameOfFile.txt"
    File also has ReadAllLines if you want the text in an array of lines.

    A lot of example code out there uses stream readers with a file stream. That allows you to not load the entire file at once, and is useful if the file is large. But if it's no more than a couple of hundred lines, you'll be fin just grabbing it all at once.

    Oh and also read the documentation.
     
  3. greglo

    greglo

    Joined:
    Aug 1, 2018
    Posts:
    13
    Thanks Baste I will plug away with that.
     
  4. greglo

    greglo

    Joined:
    Aug 1, 2018
    Posts:
    13
    I got it working; thanks to Baste players can now add custom maps.:):):)
     
    Baste likes this.