Event listener not working with firebase query

Viewed 105

I am trying to create an event listener to my firebase query script but it acts a little strange?!?

Here is my script:

using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.Events;
using Firebase.Firestore;
 
public class TestDataHandler : MonoBehaviour
{
 
    public GameObject testObject;
 
    private void Start()
    {
        fbEvent.AddListener(readyToGo);
        GetUserData("12345");
    }
 
    void readyToGo()
    {
        Debug.Log("Do Stuff");
        tetsObject.SetActive(false);
        Debug.Log("Stuff Done");
    }
 
    UnityEvent fbEvent = new UnityEvent();
 
    public void GetUserData(string userId)
    {
 
        Query query = FirebaseDataManager.instance.users
            .WhereEqualTo("userId", userId
            );
 
        query.GetSnapshotAsync().ContinueWith(querySnapshotTask =>
        {
           
            if (querySnapshotTask.IsFaulted)
            {
                Debug.Log("No userdata is found");
            }
            else if (querySnapshotTask.Result.Documents.Count() < 1)
            {
                Debug.Log("No userdata is found");
            }
            else
            {
                DocumentSnapshot userData = querySnapshotTask.Result.Documents.FirstOrDefault();
                Dictionary<string, object> data = userData.ToDictionary();
 
                User tempUser = FirebaseSerializer.FBDataToObject(data) as User;
 
                Debug.Log("Userdata found: " + tempUser.firstName);
 
                fbEvent.Invoke();
            }
        });
    }
 
}

It kinda works, course the listener listens but I am not able to, in this example, deactivate an gameobject from the listener return function.

I get the "Do Stuff" log, but not the "Stuff Done" log and the GameObject is not deactivated?

What am I missing here?

1 Answers

As the name says GetSnapshotAsync is executed async ... meaning in a different Task (similar to thread). The ContinueWith is happening after this Task is finished BUT it is NOT guaranteed to be run on the main thread.

Most of Unity's API may only be used within the Unity main thread.

For Unity specific make sure to not use ContinueWith but rather the extension method ContinueWithOnMainThread which additionally makes sure that callback is executed in the Untiy main thread so you can use the Unity API without threading issues.

Related