I'm using API calls in Unity to get an image (from the Google Street View API). I do not want to render the image immediately, rather store it in a folder. I've gone through and tried out many different code examples, but keep getting stuck on the same issue: a NullReferenceException when I try to assign the texture to it. The Texture2D is not null, in the editor it shows that it holds the image. This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class API : MonoBehaviour
{
public string URL;
public RawImage mapImage;
public Texture2D APItexture;
void Start()
{
URL = "working API url";
StartCoroutine(DownloadImage(URL));
}
IEnumerator DownloadImage(string url)
{
{
UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log(request.error);
}
else
{
APItexture = DownloadHandlerTexture.GetContent(request);
mapImage.texture = APItexture; // <- the error occurs here
}
}
}
}
In the editor, the image is visible
I have tried to assign the texture immediately, for instance like this: mapImage.texture = DownloadHandlerTexture.GetContent(request);
but to no avail.
The code is no different to any other examples online so I'm not sure where the issue could be.
Do I need to do something with the RawImage data before I can assign a texture to it?
I have little experience with both unity and stackoverflow, my apologies for any mistakes.