How to download in the background using WWW class?

Hi Guys!

I am currently evaluating Unity Pro and I just made a Patcher C# script. It does the basic thing of a patcher like CRC checks etcetera but my problem is, the processes are blocking. I need a download of WWW be asynchronous in such a way I can show an animated progress or waiting popup.

Any thoughts on how to achieve this the Unity way?

WWW already downloads in the background and doesn’t block anything. It’s inherently asynchronous, hence the isDone and progress variables. If your code blocks it’s only because you programmed it that way; typically you use WWW in a coroutine. (Although not necessarily–you could constantly poll the isDone variable in Update for example, but it’s usually much simpler and easier just to yield on the result.)

As for the question about threads, you can use threads in Unity, but you can’t access any of the Unity API outside the main thread, so you can’t use threads for the WWW class. Not that you need to.

Well. WWW class is a Coroutine so you can just yield it until it is completed.

For example:

bool isDone = false;
void IEnumerator Start() {
    WWW myW = new WWW( url );
    yield return myW;
    isDone = true;

Or 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;

Try to use WWW wrapper:

UCSS.HTTP.GetTexture(textureAddress, new EventHandlerHTTPTexture(OnTextureDownloaded));

It uses callbacks,

You can use a coroutine to download data using the WWW class, without blocking your game from running other things.

If you’d like to download data in the background (even while your game is not running), check out this plugin on the asset store: Background Download | Network | Unity Asset Store