I have a free plugin that you can check FullscreenWebGL | Camera | Unity Asset Store . Check out the FullscreenWebGLExample.cs, the FullscreenWebGL.requestFullscreen method. It uses a callback. How would I be able to change the code to use async/await? I know it’s possible because API for Firebase bindings for webgl does this, but the source code isn’t open and the author won’t reply on this matter. Does anybody know how I could do this? Thank you for your time.
Async / await in WebGL Yes it still doesn’t work.
If you still want to use async / await, you can now use async / await with an UniTask.
I want to know how though. I can use dynCall to invoke a callback, but how do I couple this with async/await? Essentially, I’d like to await the dynCall instead of passing a callback as argument to a function. Or somehow get the function that is used by the user to use async/await, while the internal function still uses the callback method.
sample code
using Cysharp.Threading.Tasks;
[DllImport("__Internal")]
private static extern void testFuncAsync(Action<int> cb);
private static UniTaskCompletionSource<int> utcs;
[MonoPInvokeCallback(typeof(Action<int>))]
private static void testFuncCB(int val)
{
utcs.TrySetResult(val);
}
public static UniTask<int> TestFuncCallAsync()
{
utcs = new UniTaskCompletionSource<int>();
testFuncAsync(testFuncCB);
return utcs.Task;
}
private async UniTask<int> Call_TestFuncCallAsync()
{
var ret = await TestFuncCallAsync();
Debug.Log($"testFuncCallAsync() Result:{ret}");
return ret;
}
mergeInto(LibraryManager.library, {
testFuncAsync: function(cb){
setTimeout(function() {
dynCall_vi(cb, 123);
}, 1000);
}
});
Awesome thank you!
hey @gtk2k do you know how to use exceptions with this? I am trying but I keep getting “Uncaught RuntimeError: unreachable”.
I have something like this, using your code
[MonoPInvokeCallback(typeof(Action<int>))]
private static void testFuncCB(int val)
{
if (val == 0)
utcs.TrySetResult(val);
else
utcs.TrySetException(new Exception("not valid"));
}
private async UniTask<int> Call_TestFuncCallAsync()
{
try {
var ret = await TestFuncCallAsync();
Debug.Log($"testFuncCallAsync() Result:{ret}");
return ret;
} catch(Exception e) {
Debug.Log("ERROR");//this never runs
Debug.Log(e.Message);
}
}
The exception I set with TrySetException doesn’t work, I get a runtimeerror:unreachable and the exception I set is never caught. I am trying and trying but can’t get this to work. Must be something silly.
it only works when it runs the TrySetResult code, but explodes if it runs the TrySetException branch.
[mention|D2LZhsyH/oBFVv8uWjbmyw==] What’s awesome is that all of this works with the regular System.Threading.Tasks library, no need to import UniTask. Apparently tasks work on webgl as long as everything is on the same thread(see stonstad’s first comment on page 2 ). According to my tests using then/catch inside jslibs don’t break this restriction. UniTask is unnecessary, using regular TaskCompletionSource works as well