question

matt-5 avatar image
matt-5 asked

Making async API calls in Unity (currently broken? it worked previously)

I have shared code to invoke the PlayFab API from either a Windows standalone app or a Unity app, and in both cases I'd like the call to be asynchronous. Below is an example method wrapping PlayFabEntityAPI.GetFiles. I took a break for a few months from working on this project, and this worked previously, but it throws a build error when I try to run the app in Unity now.

The error message seems to indicate that the WWW constructor (invoked in PlayFabWWW.cs, line 89) can't be called from a thread that's not Main, but I swear this used to work. Calling the PlayFab API from an async method in Unity has been great; I would not like to find another pattern to invoke PlayFab.

Here's the build error I'm seeing now

Create can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
UnityEngine.WWW:.ctor(String, Byte[], Dictionary`2)
PlayFab.Internal.PlayFabWww:MakeApiCall(CallRequestContainer) (at Assets/PlayFabSdk/Shared/Internal/PlayFabHttp/PlayFabWWW.cs:89)
PlayFab.Internal.PlayFabHttp:MakeApiCall(String, PlayFabRequestCommon, AuthType, Action`1, Action`1, Object, Dictionary`2, Boolean) (at Assets/PlayFabSdk/Shared/Internal/PlayFabHttp/PlayFabHTTP.cs:249)
PlayFab.PlayFabEntityAPI:GetFiles(GetFilesRequest, Action`1, Action`1, Object, Dictionary`2) (at Assets/PlayFabSdk/Entity/PlayFabEntityAPI.cs:179)
LizardBreath.<GetFileAsync>c__async4:MoveNext() (at Assets/_Core/dnd5e/Storage/PlayFab/PlayFabAsync.cs:313)
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1:Start(<GetFileAsync>c__async4&)
LizardBreath.PlayFabAsync:GetFileAsync(EntityKey)

apis
playfabasync.png (38.4 KiB)
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
brendan avatar image
brendan answered

The issue is that Unity has made a number of changes to their HTTP stack over the last few revisions. So it's quite possible that WWW has an issue, and doesn't support async. I will say that we're going to be updating to have UnityWebRequest as the default soon, but in the short term, you may want to try switching to HttpWebRequest, to see if that resolves this.

10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.