Hi I have written a singleton script called DownloadImage which can be used by any class to download images from web. There is a scene with several images with an attached script WebImage. Webimage internally calls this DownloadImage Singleton to download the image and update its image. Webimage has url field in which we can pass in the image link.
This system works fine if url is fixed. However if if I change url for ecah image component in scene images are not downloaded properly or I get error saying Malfoemed url. What might be the issue here and how to solve this?
Below is singleton Download script, and this script is attached to empty gameobject component.
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
using UnityEngine.UI;
public class DownloadImage : MonoBehaviour
{
public static DownloadImage instance;
[SerializeField] public string url;
[SerializeField] public Texture2D texture;
[SerializeField] public bool isCached;
private void Awake()
{
if (instance != null)
{
Destroy(this.gameObject);
return;
}
instance = this;
DontDestroyOnLoad(this.gameObject);
}
void Start()
{
StartCoroutine(GetImageFromWeb(url));
}
public IEnumerator GetImageFromWeb(string refURL)
{
UnityWebRequest request = UnityWebRequestTexture.GetTexture(refURL);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError ||
File.Exists(Application.persistentDataPath + "Image.jpg"))
{
Debug.Log("-------------------------" + request.error);
byte[] byteArray = File.ReadAllBytes(Application.persistentDataPath + "Image.jpg");
Texture2D tempText = new Texture2D(60, 90);
tempText.LoadImage(byteArray);
texture = tempText;
}
else
{
texture = ((DownloadHandlerTexture)request.downloadHandler).texture;
if (isCached)
{
SaveDownloadedTexture(texture);
}
}
}
public void SaveDownloadedTexture(Texture2D refTexture)
{
bool clearCache;
byte[] byteArr = refTexture.EncodeToJPG();
File.WriteAllBytes(Application.persistentDataPath + "Image.jpg", byteArr);
clearCache = Caching.ClearCache();
if (clearCache)
{
Debug.Log("Image deleted");
}
}
}
Below is script WebImage script which is attache on each of image component in scene that takes url and passes it to singleton.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WebImage : MonoBehaviour
{
[SerializeField] public string imageURL;
[SerializeField] public bool cacheData;
void Start()
{
this.gameObject.AddComponent<RawImage>();
DownloadImage.instance.url = imageURL;
DownloadImage.instance.isCached = cacheData;
}
void Update()
{
this.gameObject.GetComponent<RawImage>().texture = DownloadImage.instance.texture;
}
}