Search Unity

Bug System.IO.File doesn't work properly on WebGL platform

Discussion in 'Web' started by simple421, Jan 5, 2023.

  1. simple421

    simple421

    Joined:
    May 17, 2019
    Posts:
    18
    I'm trying to save player's data on WebGL platform but File.WriteAllBytes and File.WriteAllText works only in Awake any further calls just doesn't work and there's no exceptions in console. Everything works perfectly on other platforms (Editor, desktop mono, desktop il2cpp, android mono, android il2cpp, etc). I'm missing something?

    Unity version: 2022.1.7f1

    Code (CSharp):
    1.  
    2. // Test code
    3. public class Tester : MonoBehaviour
    4. {
    5.     private void Awake()
    6.     {
    7.          // Works
    8.         File.WriteAllText(Path.Combine(Application.persistentDataPath, "save_0.dat"), "some data");
    9.     }
    10.  
    11.     private void Update()
    12.     {
    13.          // Doesn't work
    14.         if (Input.GetKeyDown(KeyCode.Space))
    15.             File.WriteAllText(Path.Combine(Application.persistentDataPath, "save_1.dat"), "some data");
    16.     }
    17. }
    18.  
    19.  
     
  2. KamilCSPS

    KamilCSPS

    Joined:
    May 21, 2020
    Posts:
    448
    system.io is not supported on WebGL. There's no file system in a browser.
     
  3. simple421

    simple421

    Joined:
    May 17, 2019
    Posts:
    18
    I've managed to fix it:


    Code (CSharp):
    1.  
    2. #if UNITY_WEBGL
    3.             Application.ExternalEval("_JS_FileSystem_Sync();");
    4. #endif
    5.  
     
    EmeralLotus likes this.
  4. EmeralLotus

    EmeralLotus

    Joined:
    Aug 10, 2012
    Posts:
    1,462
    That's a fantastic solution.
    I'm having the same issue trying to make an existing app work for webgl.
    Can you post a more complete code of how the entire script looks with the fix.

    Cheers