Cannot change material texture with script in WebGL build (but I can in the editor/game)
I'm building a project for WebGL in unity, using universal rendering pipeline.
The scene is simple: just a cube. I assigned an URP/Lit material to the cube, and assigned a default basemap to the texture.
This renders fine in WebGL.
The problem begins when I try to fetch a texture from an URL. I have a text field in the HTML that embeds the player and I use this function to send a message to unity:
function loadit() { var url=document.getElementById('url').value; unityInstance.SendMessage('Cube','LoadTheTexture',url); }
This actually calls the following function in unity:
public async Task LoadTheTexture(string url) { _texture = await GetRemoteTexture( url );
_texture.wrapMode=TextureWrapMode.Clamp;
Renderer rend = GetComponent<Renderer>();
rend.sharedMaterial.SetTexture("_BaseMap", _texture);
return _texture;
}
I know that it works because it fetches the texture (GetRemoteTexture is a function that uses UnityWebRequestTexture.GetTexture, which works.
The console logs
"[CachedXMLHttpRequest] 'http://xxxxxxx/DSF0374-copy-scaled.jpg' downloaded successfully (743969 bytes) and stored in indexedDB cache".
However, nothing changes.
In the editor/game everything works fine - it fetches and replaces the texture of the material.
But in the WebGL build, nothing changes - the default texture remains.
Any idea what might be the cause?
GetRemoteTexture function:
public static async Task<Texture> GetRemoteTexture ( string url )
{
using( UnityWebRequest www = UnityWebRequestTexture.GetTexture( url ) )
{
//begin requenst:
var asyncOp = www.SendWebRequest();
//await until it's done:
while( asyncOp.isDone==false )
{
await Task.Delay( 1000/30 );//30 hertz
}
//read results:
if( www.isNetworkError || www.isHttpError )
{
//log error:
#if DEBUG
Debug.Log( $"{ www.error }, URL:{ www.url }" );
#endif
//nothing to return on error:
return null;
}
else
{
//return valid results:
return DownloadHandlerTexture.GetContent( www );
}
}
Your answer
Follow this Question
Related Questions
How to create GUI BUTTON from this 1 Answer
Audiosource.panStereo not works in webgl build 1 Answer
Raw Image changing texture in inspector but not in game. 1 Answer
JsonData to texture? 0 Answers