Skip to content

Instantly share code, notes, and snippets.

@kou-yeung
Created May 8, 2020 06:36
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kou-yeung/839e5d39d16a92f4f2e1209e31f20dcb to your computer and use it in GitHub Desktop.
Save kou-yeung/839e5d39d16a92f4f2e1209e31f20dcb to your computer and use it in GitHub Desktop.
Unity WebGL FileSystem Sync
using AOT;
using System;
using System.Collections.Generic;
namespace WebGL
{
public static class FileSystem
{
#if UNITY_WEBGL && !UNITY_EDITOR
[DllImport("__Internal")]
static extern void FileSystemSyncfsAddEvent(Action<int, string> action);
[DllImport("__Internal")]
static extern void FileSystemSyncfs(int id);
#else
static Action<int, string> _callback;
static void FileSystemSyncfsAddEvent(Action<int, string> action) { _callback = action; }
static void FileSystemSyncfs(int id) { _callback?.Invoke(id, ""); }
#endif
static Dictionary<int, Action<string>> callbacks = new Dictionary<int, Action<string>>();
/// <summary>
/// 静的コンストラクタ
/// 同期完了時に呼び出し内部コールバックを登録する
/// </summary>
static FileSystem()
{
FileSystemSyncfsAddEvent(Callback);
}
/// <summary>
/// 同期完了時の内部コールバック
/// </summary>
/// <param name="id"></param>
[MonoPInvokeCallback(typeof(Action<int, string>))]
static void Callback(int id, string error)
{
var cb = callbacks[id];
callbacks.Remove(id);
cb?.Invoke(string.IsNullOrEmpty(error) ? null : error);
}
/// <summary>
/// IndexedDBを同期させる
/// </summary>
/// <param name="cb">string : error</param>
public static void Syncfs(Action<string> cb)
{
var id = callbacks.Count + 1;
callbacks.Add(id, cb);
FileSystemSyncfs(id);
}
}
}
//=====================================================
// JavaScript FileSystem Plugin for UnityWebGL
//=====================================================
var LibraryFileSystem = {
$FileSystem: {
callback: null,
},
// Add Event Callback
FileSystemSyncfsAddEvent: function (cb) {
FileSystem.callback = cb;
},
// Sync
FileSystemSyncfs:function(id) {
FS.syncfs(function (err) {
var value = allocate(intArrayFromString(err?err:""), 'i8', ALLOC_NORMAL);
Runtime.dynCall('vii', FileSystem.callback, [id, value]);
});
},
};
autoAddDeps(LibraryFileSystem, '$FileSystem');
mergeInto(LibraryManager.library, LibraryFileSystem);
using UnityEngine;
public class Sample : MonoBehaviour
{
public void Syncfs()
{
WebGL.FileSystem.Syncfs((err) =>
{
if (string.IsNullOrEmpty(err))
{
Debug.Log("OK!!");
} else
{
Debug.Log("NG!!");
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment