事件侦听器不适用于 firebase 查询 [英] Event listener not working with firebase query

查看:50
本文介绍了事件侦听器不适用于 firebase 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的 firebase 查询脚本创建一个事件侦听器,但它的行为有点奇怪?!?

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

这是我的脚本:

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?

我在这里遗漏了什么?

推荐答案

顾名思义 GetSnapshotAsync 被执行 async ... 意思是在不同的 Task(类似于线程).ContinueWith 在此 Task 完成后发生但是保证在主线程上运行.

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.

Unity 的大部分 API 只能在 Unity 主线程中使用.

对于 Unity,请确保不要使用 ContinueWith 而是使用扩展方法 ContinueWithOnMainThread 这另外确保您可以在不使用回调的情况下使用主线程执行回调,从而确保您可以在不使用回调的情况下执行主线程.

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.

这篇关于事件侦听器不适用于 firebase 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆