Posted on Leave a comment

Common WWW

Unity’s WWW class is quite powerful. Give it a URL and it will download that file in the background. Provide it with some form data and it will encode it properly and post it for you. It can even load files from inside your APK on Android.

As powerful as the WWW class is, there is really only one way to use it, in a coroutine. Start the download, yield until it finishes, and finally process the error or payload. I found that nearly all times I used the WWW class the coroutine followed this pattern. So instead of rewriting it again, I made a library of the pattern.

I present the WWWNetworking library. It implements the most common WWW use patterns so you can use callbacks instead of implementing coroutines. You can also queue up multiple downloads and control the amount of concurrent downloads. It even provides singleton access to a default instance.

using UnityEngine;
using WWWNetworking;
public class FloatingImage : MonoBehaviour {
  void Start() {
    NetworkingEngineSingleton.Instance.Download("http://images.earthcam.com/ec_metros/ourcams/fridays.jpg", www => {
      GetComponent<Renderer>().material.mainTexture = www.texture;
    });
  }
}

The core of the library is the NetworkingEngine component. It is essentially a queue of tasks to run. When there are fewer than the maximum amount of allowed concurrent tasks running it starts one from the queue. The maximum is user configurable so you can dynamically change the amount of resources to consume. There is also a singleton-like default instance available for when you don’t want to deal with adding components. The example above shows the singleton-like default instance.

Leave a Reply

Your email address will not be published. Required fields are marked *