Unity Web Requests: Downloading an Image!
I recently had a go at using UnityWebRequest to download an image from the internet for use in Unity. Admittedly, this is more for the purposes of getting my head around web requests rather than for use in game development, but there could well be some neat applications 😙
To do this, try creating a new script called something like ‘DownloadImage’. Then add in the ‘using UnityEngine.Networking’ statement; this is what’ll give us access to the UnityWebRequest class among others.
Next, create a private string variable to store a URL as well as a public or serialised private RawImage or Image variable (this is what we’ll be using to display the image in the scene).
We’ll then need create a coroutine to handle the web request process. Create an IEnumerator called something like ‘GetTexture’, then create a new UnityWebRequest variable and assign ‘UnityWebRequestTexture.GetTexture([image URL string variable])’ to it. Doing so will prepare the specific request we want to make, in this case a ‘GetTexture’ request.
We can then both send and wait (or ‘yield return’) for this request using the statement ‘yield return [UnityWebRequest variable].SendWebRequest()’. Once the request is complete, the program will continue onto whatever code follows in the IEnumerator. In the case of a web request, the main thing we’ll want to do is to check whether the request was successful. An if statement checking for whether ‘[UnityWebRequest variable].isHttpError’ or ‘[UnityWebRequest variable].isNetworkError’ should catch our most likely errors, and we can even debug this information by printing ‘[UnityWebRequest variable].error’ to the console. In our else statement, we can store the successfully-retrieved image into a variable. We could store this in a Texture2D variable, but ‘var’ could give us a bit more flexibility. Finally, we can assign this variable to our RawImage’s texture or to our Image’s sprite.
You might have already done this, but we’ll need some way to call this IEnumerator in the first place, so we could just check for a key press in the Update method and then trigger the coroutine that way. For the complete code, I’ve included it here:
Heading back into Unity, you’ll need to assign this script to a GameObject in your scene, then specify both the URL of the image you want to use as well as the Image or RawImage component you want to display it on.
With that done, you should now be ready to head into Play mode and give it a whirl! I’ve added in a little prompt and success/error message to the display, but aside from that you should have something that’ll look and work like this one:
Hope this helps! I’ll cover retrieving and working with (JSON) text using a web request in a subsequent article 😉