One way to store and read text file data is to store the text files on the Web. In this recipe, the contents of a text file for a given URL is downloaded, read, and then displayed.
For this recipe you will need to have access to files on a web server. If you run a local web server such as Apache, or have your own web hosting, then you could use the files in the 0423_07_01
folder and the corresponding URL. Otherwise, you may find the following URLs useful since they are the web locations of an image file (a Packt logo) and a text file (an "ASCII-art" badger picture):
// file: ReadWebImageTexture.cs using UnityEngine; using System.Collections; public class ReadWebImageTexture : MonoBehaviour { public string url = "http://www.packtpub.com/sites/default/files/packt_logo.png"; private Texture2D externalImage; private void Start () { StartCoroutine( LoadWWW() ); } private void OnGUI() { GUILayout.Label ( "url = " + url ); GUILayout.Label ( externalImage ); } private IEnumerator LoadWWW(){ yield return 0; WWW imageFile = new WWW (url); yield return imageFile; externalImage = imageFile.texture; }
When the game starts, our Start()
method starts the LoadWWW()
co-routine method. A co-routine is a method that can keep on running in the background without halting or slowing down the other parts of the game and the frame rate. The yield
statement indicates that once a value can be returned for imageFile
, the remainder of the method can be executed, that is, until the file has finished downloading, no attempt should be made to extract the texture
property of the WWW
object variable.
For each frame our OnGUI()
method displays the contents of url
string variable and attempts to display the externalImage
texture image.
18.225.234.24