Loading external text files using C# file streams

For standalone executable games that both read from and write to (create or change) text files, .NET data streams are often used for both reading and writing. A later recipe illustrates how to write text data to files, while this recipe illustrates how to read a text file.

Note

This technique only works when you compile to a Windows or Mac standalone executable; it will not work for Web Player builds, for example.

Getting ready

For this recipe, you'll need a text file; two of these have been provided in the 0423_08_01 folder.

How to do it...

To load external text files using C# file streams, perform the following steps:

  1. Create a new C# script called FileReadWriteManager:
    // file: FileReadWriteManager.cs
    using System;
    using System.IO;
    
    public class FileReadWriteManager {
        public void WriteTextFile(string pathAndName, string stringData) {
            // remove file (if exists)
            FileInfo textFile = new FileInfo(  pathAndName ); 
            if( textFile.Exists )
                textFile.Delete();
    
            // create new empty file
            StreamWriter writer; 
            writer = textFile.CreateText(); 
    
            // write text to file
            writer.Write(stringData); 
    
            // close file
            writer.Close(); 
        }
    
        public string ReadTextFile(string pathAndName) { 
            string dataAsString = "";
    
            try {
                // open text file
                StreamReader textReader = File.OpenText( pathAndName );
    
                // read contents
                dataAsString = textReader.ReadToEnd();
    
                // close file
                textReader.Close();
    
            }
            catch (Exception e) {
                //display/set e.Message error message here if you wish
    
            }
    
            // return contents
            return dataAsString; 
        }
    }
  2. Add the following C# script to Main Camera:
    // file: ReadWithStream.cs
    using UnityEngine;
    using System.Collections;
    using System.IO;
    
    public class ReadWithStream : MonoBehaviour {
        private string filePath = "";
        private string textFileContents = "(file not found yet)";
        private FileReadWriteManager fileReadWriteManager = new FileReadWriteManager();
    
        private void Start () {
            string fileName = "cities.txt";
            filePath = Path.Combine(Application.dataPath, "Resources");
            filePath = Path.Combine(filePath, fileName);
    
            textFileContents = fileReadWriteManager.ReadTextFile( filePath );
        }
    
        private void OnGUI() {
            GUILayout.Label ( filePath );
            GUILayout.Label ( textFileContents );
        }
    }
  3. Build your (Windows, Mac, or Linux) standalone executable. You'll need to save the current scene and then add this to the scenes in the build.
  4. Copy the text file containing your data into your standalone's Resources folder (that is, the filename you set in the first statement in the Start() method—in our listing, this is the cities.txt file)

    Note

    You will need to place the files in the Resources folder manually after every compilation.

    For Windows and Linux users: When you create a Windows or Linux standalone executable, there is a _Data folder that is created with the executable application file. The Resources folder can be found inside this data folder.

    For Mac users: A Mac standalone application executable looks like a single file, but it is actually a Mac OS "package" folder. Right-click on the executable file and select Show Package Contents. You will then find the standalone's Resources folder inside the Contents folder.

How it works...

When the game runs, the Start() method creates the filePath string and then calls the ReadTextFile() method from the fileReadWriteManager object, to which it passes it the filePath string. This method reads the contents of the file and returns them as a string, which is stored in the textFileContents variable. Our OnGUI() method displays the values of these two variables (filePath and textFileContents).

Note

Note the need to use the System.IO package for this recipe. The C# script FileReadWriteManager.cs contains two general purpose file read and write methods that you may find useful in many different projects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.232.11