unity-game-enginenullreferenceexceptionrawimage

Can't assign Texture2D to RawImage in Unity (C#) - NullReferenceException


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.


Solution

  • There's some mistake in the way you are reasoning about the problem. The NullReferenceException is not about your Texture2D, but the mapImage in your code.

    you are trying to assign the Texture2D to the raw image mapImage.texture = APItexture; but there's no mapImage, and as consequence, you cannot assign a texture to it. The .texture is a property of the RawImage, unless you have referenced or created it before, this call will always throw the exception.

    Your own image show that the mapImage is empty with the none label in it. You need a mapImage first to work. Please take a look at the Max comment about NullReferenceException.