c# - 从 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!!!");
}
});
}
}
当我运行这个脚本时,只显示“完成!” 在日志控制台登录。更改场景脚本及其下方,例如我想写日志“完成!!!” 场景改变后,不执行。
解决方案
这是 Unity 中使用 Firebase 的经典任务延续问题。使用时,ContinueWith
不保证在Unity主线程上调用。您尝试执行的操作SceneManager.LoadSceneAsync()
需要在 Unity 主线程上执行。如果您尝试访问内部的 GameObjects ContinueWith
,即使这样也会失败。代码只是在控制台中出现,没有任何错误。
解决方案:而不是ContinueWith
使用Firebase 扩展ContinueWithOnMainThread
,正是出于这个原因。
推荐阅读
- ruby-on-rails - 为顺序嵌套资源创建 link_to
- java - 遇到 SQLException 问题,使用 executeUpdate 获取 executeQuery 错误
- sql - 连接 2 个多对多关系表
- vim - vim NERDTree 无法打开文件
- javascript - 怎么说浏览器开始下载文件?
- jquery - 如何修复 php 文件中的 bootstrapValidator 错误
- c++ - C++ 跨平台:我的 MAC 地址是什么
- javascript - d3 v5 力模拟:如何使用停止和刻度
- java - 意外令牌(位置:TEXT "@1:2 in java.io.InputStreamReader@3422132)
- javascript - jquery,更改附加标签的顺序