Search Unity

Discussion WriteAllBytesAsync and ReadAllBytesAsync don't work with WebGL

Discussion in 'Scripting' started by abnerdev, May 3, 2023.

  1. abnerdev

    abnerdev

    Joined:
    Mar 10, 2018
    Posts:
    2
    Hey, if anything I want this post to show up when someone googles for this, because I had to find this out on my own.

    For those who don't know, WebGL is single threaded - which means any multi-threaded resources won't work in it. A common example is the WebClient library, which should be replaced by the WebRequest library, and more.

    That doesn't mean Async and Tasks in general aren't supported - because asyncronous task based programming isn't multi threaded - this is a common misconception.

    That said, specifically the WriteAllBytesAsync and ReadAllBytesAsync don't work. This probably means they are multi threaded in their inner workings or there's some other reason I don't know (if someone does, I'm really curious to know)

    This is how I've tested it:

    Code (CSharp):
    1. using System.IO;
    2. using UnityEngine;
    3.  
    4. public class TestingWriteReadInWebGL : MonoBehaviour
    5. {
    6.  
    7.     [SerializeField] private Texture2D tex;
    8.    
    9.     async void Start()
    10.     {
    11.         string path = Application.persistentDataPath + "/TestPic.png";
    12.         Debug.Log("Writing to path/url: " + path);
    13.         byte[] data = tex.GetRawTextureData();
    14.         Debug.Log("Data: " + new string(System.Text.Encoding.UTF8.GetString(data).ToCharArray()));
    15.         await File.WriteAllBytesAsync(path, data);
    16.         Debug.Log("Tried writing to path/url: " + path);
    17.         byte[] bytes = await File.ReadAllBytesAsync(path);
    18.         Debug.Log("Read from path/url: " + path);
    19.         Debug.Log("Data: " + new string(System.Text.Encoding.UTF8.GetString(bytes).ToCharArray()));
    20.     }
    21. }
    22.  
    Replace them with their non async counterparts and it works. So I guess we just gotta deal with it.

    That's it :)
     
    Marble and colin-defais like this.