-
-
Save Kasiviswanathan3876/2cffec271d748a9925307f0fd025f330 to your computer and use it in GitHub Desktop.
Unity Image Downloader example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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