Download and assign a Texture without creating a new one.

Firstly, some background:

I’m developing a project for the Oculus GO, which is a relatively low spec device. As a result, if I create textures at runtime the app will result in a crash.

My app needs to download and set images at runtime and so far I have been able to bypass this issue by having the texture defined beforehand and loading it using the following code:

//I Define a variable that will hold the texture
private Texture2D background = new Texture2D(4096, 2048);

//The code that downloads an Image and sets it as background
using (WWW www = new WWW(imagePath))
{
    yield return www;
    www.LoadImageIntoTexture(background);
    RenderSettings.skybox.mainTexture = background;
}

But as of 2018.3 I have noticed that www is obsolete, so I tried switching to the recommended UnityWebRequest. This however seems to force you into creating a new instance of a 2DTexture, which results in the forementioned memory/performance related crash. This is the code I tried:

//I Define a variable that will hold the texture
private Texture2D background = new Texture2D(4096, 2048);

//The code that downloads an Image and sets it as background. Setting the nonReadable argument to true/false doesn't seem to solve anything
using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(imagePath, true))
{
    yield return www.SendWebRequest();
    background = DownloadHandlerTexture.GetContent(www);
    RenderSettings.skybox.mainTexture = background;
}

Is there another way of doing this without relying on obsolete classes?

Use Get instead of GetTexture (to use DownloadHandlerBuffer).
Then load image to texture using this API: https://docs.unity3d.com/ScriptReference/ImageConversion.LoadImage.html

This is the same API that is used by WWW internally.

1 Like

Thank you this works like a charm:

using (UnityWebRequest uwr = UnityWebRequest.Get(imagePath))
{
    yield return uwr.SendWebRequest();
    background.LoadImage(uwr.downloadHandler.data);
    RenderSettings.skybox.mainTexture = background;
}
1 Like