Loading external resource files – by downloading files from the Internet

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.

Getting ready

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):

How to do it...

  1. Add the following C# script to the Main Camera:
    // 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;
      }
  2. Play the scene. Once downloaded, the contents of the image file will be displayed.

How it works...

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.

See also

  • The Loading external resource files – by Unity Default Resources recipe.
  • The Loading external resource files – by manually storing files in Unity's Resources folder recipe.
..................Content has been hidden....................

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