Hello,
Your problem is here:
while (!unityServicesTask.IsCompleted)
{
i++;
}
This code will manually âwaitâ until the task has completed synchronously. It breaks the purpose of using async in the first place, and wont work since it wont let the task actually run.
UnityWebRequests run as coroutines on the main thread, so you canât do that. You basically need to keep a state-machine. UnityServices.Instance.State
does this for you
That is the purpose of async. If you await immediately when you call the function, you just release control to the caller of my function.
This is accurate, specially because we have async void
, so the caller cannot wait. Not sure why you have async void at that level though.
Anyway, the game should not freeze.
This is not accurate, just because something is async, it doesnt not mean that it will necessarily run on a different thread. It could run as a co-routine. Async makes no guarantees about threading. Only about the state machine.
This is probably what it looks like internally (somwhere down the line)
var tcs = new TaskCompletionSource<ApiResponse>();
var requestOperation = request.SendWebRequest();
var registration = cancellationToken.Register(() => Abort(request));
requestOperation.completed += _ => OnCompleted(tcs, request, registration);
return tcs.Task;
Anyway, moving on, instead, its better to spin on your update loop:
bool callbackDone = false;
public void Update() {
if (UnityServices.Instance.State == ServicesInitializationState.Uninitialized || callbackDone )
return;
callbackDone = true;
OnUnityServicesInitilized?.Invoke();
}
Or better yet, just use the built-in callback:
UnityServices.Instance.Initialized += ...
This is correct. Not that you need to, it effectively runs as a co-routine, using await is fineâŚ
Hereâs a simple example you should try out to better understand async:
public async void Start() {
await Task.Delay(3000);
Debug.Log("Will this run before or after the first update call");
}
public async void Update() {
Debug.Log("Update part 1 Will this happen every second, or every frame?")
await Task.Delay (1000);
Debug.Log("Update part 2 Will this happen every second, or every frame?")
}