- Home /
Question by
JopRillos2001 · May 25, 2021 at 10:23 AM ·
networkingspriteimagewebrequesturl
How can I fill a list with images from an external source?
I have made a JSON file which contains items. Each item also has an image. The JSON file contains image URL's to images online. I want to use these images in my game. Ive made an item class which looks like this:
public class Items
{
public string Name;
public string Type;
public string ImgPath;
public Sprite Image;
}
The JSON file fills the first 3 strings. The Image attribute should be filled using the URL. I have found solutions to get images from URL using UnityWebRequest. This results in a single image being retrieved, but I cant seem to figure out how to fill my list with images in order to display them in my game.
Ive been stuck on this for a while now, any help will be appreciated.
This is my WebRequests class:
public static class WebRequests
{
private class WebRequestsMonobehaviour : MonoBehaviour { }
private static WebRequestsMonobehaviour webRequestsMonobehaviour;
private static void Init() {
if (webRequestsMonobehaviour == null) {
GameObject gameObject = new GameObject("WebRequests");
webRequestsMonobehaviour = gameObject.AddComponent<WebRequestsMonobehaviour>();
}
}
public static void GetImage(string url, Action<string> onError, Action<Texture2D> onSuccess)
{
Init();
webRequestsMonobehaviour.StartCoroutine(DownloadImage(url, onError, onSuccess));
}
static IEnumerator DownloadImage(string url, Action<string> onError, Action<Texture2D> onSuccess)
{
using (UnityWebRequest unityWebRequest = UnityWebRequestTexture.GetTexture(url))
{
yield return unityWebRequest.SendWebRequest();
if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
{
onError(unityWebRequest.error);
}
else
{
onSuccess(((DownloadHandlerTexture)unityWebRequest.downloadHandler).texture);
}
}
}
}
And this is how I'm able to retrieve 1 image:
WebRequests.GetImage(url,
(string error) =>
{
Debug.Log("Error: " + error);
},
(Texture2D texture) =>
{
Debug.Log("Succes");
Sprite sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f);
transform.GetChild(0).GetComponent<Image>().sprite = sprite;
});
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613034141im_/https://answers.unity.com/themes/thub/images/avi.jpg)