简体   繁体   中英

Issue retrieving data from Firebase Database and saving data on unity

I am using the following code to retrieve data from Firebase database on a user with Unity3D, in our case i am getting User Level:

 FirebaseDatabase.DefaultInstance
   .GetReference("users").Child(userID)
   .GetValueAsync().ContinueWith(task =>
   {
       if (task.IsFaulted)
       {
           Debug.LogError("Error retriving user data: " + userID);
         // Handle the error...
       }
       else if (task.IsCompleted)
       {
           DataSnapshot snapshot = task.Result;
           int TempUserLevel = (int)snapshot.Child("Level").Value; 
          //this get's an error 
           PlayerPrefs.SetInt(_UserLevel, TempUserLevel);

       }
   }

Error:

TrySetInt can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene.

As I understand the TASK is a new thread and not Unity Main thread. Still I can't seem save values locally on unity, or get the value out of the TASK.

It cannot be called because continue with is a delegate and it waits for response. What I did is just made a waituntil coroutine before calling this delegate using and set a bool for instance some bool check = false.

else if(task.IsCompleted)
    {
     // your operation
     check=true;

    }
    ////////
IEnumerator myRoutine()
  {
         yield return new WaitUntil ( () => check );
         // set your playerprefs.

  }

实际上,您可以将“ContinueWith”更改为“ContinueWithOnMainThread”。

You can change ContinueWith to ContinueWithOnMainThread, but you will need add "using Firebase.Extensions;"

using Firebase.Extensions;

FirebaseDatabase.DefaultInstance.GetReference("users").Child(userID)
  .GetValueAsync().ContinueWithOnMainThread(task => 
{
    if (task.IsFaulted) 
    {
      // Handle the error...
    }
    else if (task.IsCompleted) 
    {
      DataSnapshot snapshot = task.Result;
      // Do something with snapshot...
    }
});

See documentation for more examples: https://firebase.google.com/docs/database/unity/retrieve-data

Potential Note: If you are following documentation for Google Sign in with Firebase and downloaded the Firebase SDK for Unity 2020, you may get an error regarding a conflict with System.Threading.Tasks (this happened to me). If anyone else gets this error, it can be dealt with by deleting or renaming the Unity.Compat and Unity.Tasks files under Unity > Assets > Parse > Plugins, but do not change or delete the files in the dotNet45 folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM