Reading data from a text file
Text files are used to store and communicate data for many purposes. Unity makes it easy for you to read in the contents of a text file via the built-in TextAsset
script class. In this recipe, you’ll add a UI Text item to a scene, and then write a script that at runtime will read the contents from the text file and display them to the player.
Figure 10.4: Showing the text file contents on screen at runtime
Getting ready
You can use any text file as the data for this recipe. We’ve provided a small text file containing a list of cities, in a cities.txt
file in the 10_03 folder.
Figure 10.5: Contents of the text file cities.txt
How to do it...
To read data from a text file, perform the following steps:
- Create a new Unity 2D project.
- Import the provided cities.txt text file into the project (or use some other text file you have on your computer).
- Load the TextMeshPro essentials resources...