[ad_1]
Hi I’ve written a singleton script known as DownloadImage which can be utilized by any class to obtain photos from net. There is a scene with a number of photos with an connected script InternetImage. Webimage internally calls this DownloadImage Singleton to obtain the picture and replace its picture. Webimage has url area wherein we will go within the picture hyperlink.
This system works high quality if url is fastened. However if if I modify url for ecah picture part in scene photos will not be downloaded correctly or I get error saying Malfoemed url. What may be the problem right here and how one can clear up this?
Below is singleton Download script, and this script is connected to empty gameobject part.
utilizing System.Collections;
utilizing System.Collections.Generic;
utilizing System.Threading.Tasks;
utilizing UnityEngine;
utilizing UnityEngine.Networking;
utilizing System.IO;
utilizing UnityEngine.UI;
public class DownloadImage : MonoBehaviour
{
public static DownloadImage occasion;
[SerializeField] public string url;
[SerializeField] public Texture2D texture;
[SerializeField] public bool isCached;
non-public void Awake()
{
if (occasion != null)
{
Destroy(this.gameObject);
return;
}
occasion = 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 InternetImage script which is connected on every of picture part in scene that takes url and passes it to singleton.
utilizing System.Collections;
utilizing System.Collections.Generic;
utilizing UnityEngine;
utilizing UnityEngine.UI;
public class InternetImage : MonoBehaviour
{
[SerializeField] public string imageURL;
[SerializeField] public bool cacheData;
void Start()
{
this.gameObject.AddComponent<UncookedImage>();
DownloadImage.occasion.url = imageURL;
DownloadImage.occasion.isCached = cacheData;
}
void Update()
{
this.gameObject.GetComponent<UncookedImage>().texture = DownloadImage.occasion.texture;
}
}
[ad_2]