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. Dismiss Notice

Reading from a text file [SOLVED]

Discussion in 'Scripting' started by NoXlenS, Jan 16, 2015.

  1. NoXlenS

    NoXlenS

    Joined:
    Jan 14, 2015
    Posts:
    5
    Hi everyone,

    I am new to unity and am learning to code in C#.

    The 2D application i am developing in unity requires random short messages from a database to be displayed. I was wondering how i would code the script to read from a text file and extract the messages like:

    msg.txt:
    Hello!
    Nice, looking good!
    Take that!
    ...

    Where each line can be in its own separate string (maybe in a string[]) The text file would be updated periodically so I would need to read from it.

    I've searched the forums a bit and there are similar questions but in JS, so I attempted to modify some of it:

    StreamReader f = new StreamReader(Application.dataPath/"Resources/msg.txt");
    string fileContents = f.ReadToEnd();

    but that doesnt seem to work :(

    So could anyone help point me in the right direction? :D
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
  3. NoXlenS

    NoXlenS

    Joined:
    Jan 14, 2015
    Posts:
    5
    Thanks for the reply, although I found a simpler way to obtain the string from the file.

    For those wondering, I used:

    string f = Resources.Load ("msgDB").ToString(); // from Resources/msgDB.txt
    string[] msgDB = f.Replace("\r\n","\n").Replace("\r","\n").Split("\n"[0]);

    To store the strings into an array.