首页 > 解决方案 > 从 Firebase 获取数据后尝试更改场景时,Unity 脚本停止工作

问题描述

因此,当我尝试从 Firebase 实时数据库中获取数据时,数据已成功接收。但是当我试图改变场景时,脚本只是停止工作。这是我的完整脚本:

using Firebase;
using Firebase.Database;
using Firebase.Extensions;
using Firebase.Unity.Editor;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class NewBehaviourScript : MonoBehaviour
{
    DependencyStatus dependencyStatus = DependencyStatus.UnavailableOther;
    protected bool isFirebaseInitialized = false;
    // Start is called before the first frame update
    private void Start()
    {

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
            dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                InitializeFirebase();
            }
            else
            {
                Debug.LogError(
                  "Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });
    }
    protected virtual void InitializeFirebase()
    {
        FirebaseApp app = FirebaseApp.DefaultInstance;
        // NOTE: You'll need to replace this url with your Firebase App's database
        // path in order for the database connection to work correctly in editor.
        app.SetEditorDatabaseUrl("https://frim-exam.firebaseio.com/");
        if (app.Options.DatabaseUrl != null)
            app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
        StartListener();
        isFirebaseInitialized = true;
    }

    void StartListener()
    {
        FirebaseDatabase.DefaultInstance
      .GetReference("Leaders")
      .GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted)
            {
                // Handle the error...
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
              // Do something with snapshot...
              Debug.Log("Done!");
              SceneManager.LoadSceneAsync("Scene2");
              Debug.Log("Done!!!");
          }
        });
    }
}

当我运行这个脚本时,只显示“完成!” 在日志控制台登录。更改场景脚本及其下方,例如我想写日志“完成!!!” 场景改变后,不执行。

标签: c#firebaseunity3dfirebase-realtime-database

解决方案


这是 Unity 中使用 Firebase 的经典任务延续问题。使用时,ContinueWith不保证在Unity主线程上调用。您尝试执行的操作SceneManager.LoadSceneAsync()需要在 Unity 主线程上执行。如果您尝试访问内部的 GameObjects ContinueWith,即使这样也会失败。代码只是在控制台中出现,没有任何错误。

解决方案:而不是ContinueWith使用Firebase 扩展ContinueWithOnMainThread,正是出于这个原因。


推荐阅读