Tuesday, April 8, 2014

How to download content or picture image in the background using WWW class?

 Unity3D has a utility module for retrieving the contents of URLs named as WWW class. WWW class can also download a picture image,  so that you can assign that picture on the internet as a Texture in your Unity3D project.



Remember, WWW class is a Coroutine and runs background.

I can recommend two different ways of implementing background downloading in Unity3D.

First way; You can just yield it until it is completed. For example:

void IEnumerator Start() {
    WWW www = new WWW( url );
    yield return www;
   Texture2D myPicture = www.texture;  //this is how you download and image from web in untiy3d.
}


Second Way;  you can inspect the isDone property of WWW class to see if the download has completed or not. Here is an example of using the isDone and progress properties:

float progress = 0.0f;
void IEnumerator Start() {
    WWW myW = new WWW( url );
    while( !myW.isDone )
    {
        progress = myW.progress;
        yield return null;
    }
    progress = 1.0f;
}

Tip: You can create a progress bar with that progress property in OnGUI function.



No comments:

Post a Comment