Loading external text files using the TextAsset public variable

A straightforward way to store data in text files and then choose between them before compiling is to use a public variable of the class TextAsset.

Note

This technique is only appropriate when there will be no change to the data file after game compilation.

Getting ready

For this recipe, you'll need a text (.txt) file. In the 0423_08_01 folder, we have provided two such files:

  • cities.txt
  • countries.txt

How to do it...

To load external text files using TextAsset, perform the following steps:

  1. Import the text file you wish to use into your project (for example, cities.txt)
  2. Add the following C# script to Main Camera:
    // file: ReadPublicTextAsset.cs
    using UnityEngine;
    using System.Collections;
    
    public class ReadPublicTextAsset : MonoBehaviour {
        public TextAsset dataTextFile;
        private string textData = "";
    
        private void Start() {
            textData = dataTextFile.text;
        }
    
        private void OnGUI() {
            GUILayout.Label ( textData );
        }
    }
  3. With Main Camera selected in the Hierarchy view, drag the cities.txt file into the public string variable dataTextFile in the Inspector view.

How it works...

The contents of the text file are read from the dataTextFile TextAsset object and stored as a string into textData. Our OnGUI() method displays the contents of textData as a label.

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

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