Load from Text Files at runtime

Hello all,

Recently, I put out a game with my own dialogue system.
I used a WPF Program to parse text files in my own proprietary format, and the Unity to load the information back from the file.

It all works on Windows. However, I have not gotten it to work on any other platform (I’ve tried Mac and WebGL).

WebGL is the real goal here.

The Non-Windows section doesn’t do anything right now.

The issue is, I don’t know how to store the .txt files in Unity in a way that they can be packaged with the project and loaded from at Runtime.

Normally, that’s a job for Resources.Load, but I don’t know what data type I would use.

My script to load the text files is this massive function:

    //This version can take in a file name
    public void LoadFile(string file)
    {
        fileName = file;
        LoadFile();
    }

    void LoadFile() //set filename before loading
    {
        if (windows)//This only works if we're on Windows
        {

            try
            {
                //string fileName = ChooseFile();
                //Now actually load the file
                if (File.Exists(fileName))
                {

                    string[] textInput = File.ReadAllLines(fileName);//read whole file

                    //Clear the set of lines, so we don't read from the beginning again.
                    Lines.Clear();

                    int caseNum = 0;
                    string status = "working";
                    Line temp = new Line(); //to hold info, before it's added to Lines
                                            //Now slice it into bitty bits!
                    foreach (string lineInput in textInput)
                    {
                        if (status == "working")
                        {
                            switch (caseNum % 5)    //casenum keeps counting up, and we use it mod 5
                            {
                                case 0: //Name of speaker
                                        //If line has 1+ characters (Because saved files tend to have an empty line at end
                                    if (lineInput.Length > 0)
                                    {
                                        temp.speaker = lineInput;
                                        //Also add it to the dropdown list if not already on it
                                        //AddToCharBox(lineInput); //McDialogue Tool Only
                                    }
                                    else
                                        Debug.Log("Blank Name Detected");
                                    //No error for name being blank, in the event of narration or something.
                                    ///Seems like a dumb idea, but I can change it later. 
                                    caseNum++;
                                    break;

                                case 1: //Info line 1:  Anim, sound, sprite
                                    if (lineInput.Length >= 7)
                                    {

                                        //anim
                                        string raw = lineInput.Substring(0, 2);  //Substring: (starting position, count)
                                        temp.anim = System.Convert.ToInt32(raw);   //using System

                                        temp.sound = System.Convert.ToInt32(lineInput.Substring(3, 2));//sound
                                        temp.sprite = System.Convert.ToInt32(lineInput.Substring(6, 2));//sprite

                                        caseNum++;
                                    }
                                    else
                                    {
                                        Debug.Log("Syntax Error on Info Line 1");
                                        status = "FAIL - Syntax Error";
                                    }
                                    break;

                                case 2: //Info line 2 - Size, style, font-face
                                    if (lineInput.Length >= 5)
                                    {
                                        temp.size = System.Convert.ToInt32(lineInput.Substring(0, 3));//Font Size Modifier
                                        temp.fontStyle = System.Convert.ToInt32(lineInput.Substring(4, 1));//Font Style Modifier
                                        if (lineInput.Length >= 6)//prevent substring out of range error
                                            temp.fontFace = lineInput.Substring(6);//Font FACE Modifier - takes a string until end of line.  Can be absent
                                        caseNum++;
                                    }
                                    else
                                    {
                                        Debug.Log("Syntax Error on Info Line 2");
                                        status = "FAIL - Syntax Error";
                                    }
                                    break;

                                case 3: //Final Info line:  Stop and comment
                                    if (lineInput.Length >= 1)
                                    {
                                        temp.stop = System.Convert.ToInt32(lineInput.Substring(0, 1));//Font Style Modifier

                                        /*
                                         * Use something like this to include Comment with the Line class.  
                                         * Currently: Not implemented.
                                        if (lineInput.Length >= 6)//prevent substring out of range error
                                            temp.fontFace = lineInput.Substring(6);//Font FACE Modifier - takes a string until end of line.  Can be absent
                                         */
                                        caseNum++;
                                    }
                                    else
                                    {
                                        Debug.Log("Syntax Error on Info Line 3");
                                        status = "FAIL - Syntax Error";
                                    }
                                    break;

                                case 4: //The text of a line.  Unless we get to seperator, don't add line.
                                        //Keep adding to Details until we get to seperator
                                    if (lineInput == seperator)  //once we get to seperator, dump detailsTemp into details list and then continue switching
                                    {
                                        //idk, but I don't think this is needed:  lines.Add((linesTemp + "\n"));    //should add a newline between lines in the text file

                                        Lines.Add(temp);    //Add temp to lines

                                        temp = new Line();  //Resets temp

                                        //Does a cool thing while reading
                                        if (Lines.Count % 3 > 0)
                                            Debug.Log("Line read successfully.");
                                        else if (Lines.Count % 3 > 1)
                                            Debug.Log("Line read successfully..");
                                        else
                                            Debug.Log("Line read successfully...");
                                        //Even cooler: TODO Make it so that for each line read, one more dot appears

                                        caseNum++;
                                    }
                                    else
                                    {
                                        temp.line += lineInput;    //adds lines to details temp until we get to seperator
                                        temp.line += "\n";
                                    }

                                    break;
                            }
                        }
                    }

                    //Success
                    Debug.Log("Load complete! " + fileName);
                    Debug.Log("Lines: " + Lines.Count);
                    //ListViewRefresh(); //Only needed in McDialogue PArser
                    //If this contains only one line, set lastline = true
                    if (Lines.Count == 1)
                    {
                        lastLine = true;
                        oneLine = true;    //Prevents InputMan from setting lastLine to false
                    }
                    else
                        oneLine = false;
                    //Now, output first line
                    currentLine = -1;
                    NextLine();

                }
                else
                {
                    Debug.Log("File not found: " + fileName);

                }

            }
            catch (System.Exception ex)
            {
                Debug.Log("Error while loading file.\n" + ex.Message);
            }
        }
///END OF WINDOWS SECTION
///BEGIN NON-WINDOWS SECTION
        else if (Resources.Load(fileName) != null)
        {
            Debug.Log("Trying to load using Resources.Load...");
            var thisFile = Resources.Load(fileName);
            Debug.Log(thisFile.GetType());

            //Here is where it all falls apart, since I used File.Load, which maybe only works on WindowS???
           
            //Success
            Debug.Log("Load complete! " + fileName);
            Debug.Log("Lines: " + Lines.Count);
            //ListViewRefresh(); //Only needed in McDialogue PArser
            //If this contains only one line, set lastline = true
            if (Lines.Count == 1)
            {
                lastLine = true;
                oneLine = true;    //Prevents InputMan from setting lastLine to false
            }
            else
                oneLine = false;
            //Now, output first line
            currentLine = -1;
            NextLine();
        }
        else
            Debug.Log("Both load methods failed");

    }

TLDR; I’m loading info from text files, using File.Load , but I want to make it WebGL compatible.

If the text files are treated as assets and put in the resources folder, they can be loaded using Resources.Load on any platform as a TextAsset so you don’t need to run platform specific code. However you cannot modify the text file once its built, it will be serialized with the rest of the assets.

1 Like

Thank you so much! It works flawlessly.
Awesome, I’m really excited to put this game onto WebGL.

1 Like