Skip to content

Instantly share code, notes, and snippets.

@StephenHodgson
Last active June 7, 2019 19:16
Show Gist options
  • Save StephenHodgson/c6a16f02a684991294451ff62bd9ffbd to your computer and use it in GitHub Desktop.
Save StephenHodgson/c6a16f02a684991294451ff62bd9ffbd to your computer and use it in GitHub Desktop.
Unity Image Downloader example
using System;
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class DownloadHelper : MonoBehaviour
{
private string userName = string.Empty;
private string password = string.Empty;
public delegate void ImageDownloaded(Texture2D image);
public event ImageDownloaded OnImageDownloaded;
private string GetBasicAuthHeader()
{
var auth = string.Format("{0}:{1}", userName, password);
auth = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));
return string.Format("Basic {0}", auth);
}
public void DownloadImage(string uri)
{
StartCoroutine(RunImageDownload(uri));
}
private IEnumerator RunImageDownload(string uri)
{
using (var request = UnityWebRequest.Get(uri))
{
// If you need authorization for the REST API
// request.SetRequestHeader("Authorization", GetBasicAuthHeader());
request.Send();
while (!request.isDone)
{
if (request.downloadProgress > -1)
{
// Display loading progress bar or whatever you need
}
}
// Clear your progress bar
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError("Network Error: " + request.error);
yield break;
}
Debug.Log("Network Response: " + request.responseCode);
// Load the image data
var imageData = request.downloadHandler.data;
var downloadedImage = new Texture2D(0, 0);
downloadedImage.LoadImage(imageData);
if (OnImageDownloaded != null)
{
OnImageDownloaded.Invoke(downloadedImage);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment