我正在尝试使用 Unity 从 Firebase 的实时数据库接收 JSON 值。
我执行以下操作:
FirebaseDatabase.DefaultInstance
.GetReference("Leaders").OrderByChild("score").GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogError("error in reading LeaderBoard");
return;
}
else if (task.IsCompleted)
{
Debug.Log("Received values for Leaders.");
string JsonLeaderBaord = task.Result.GetRawJsonValue();
callback(JsonLeaderBaord);
}
}
});
尝试阅读回调:
private string GetStoredHighScores()
{
private string JsonLeaderBoardResult;
DataBaseModel.Instance.RetriveLeaderBoard(result =>
{
JsonLeaderBoardResult = result; //gets the data
});
return JsonLeaderBoardResult; //returns Null since it doesn't wait for the result to come.
}
问题是我如何等待回调返回值,然后 return
是JsonLeaderBoardResult
.
return JsonLeaderBoardResult;
// 返回 Null,因为它不等待结果到来。
该RetriveLeaderBoard
函数不会立即返回。您可以使用协程等待它或JsonLeaderBoardResult
通过Action
. Action
在您的情况下使用更有意义。
将字符串返回类型更改为 void 然后通过Action
以下方式返回结果:
private void GetStoredHighScores(Action<string> callback)
{
string JsonLeaderBoardResult;
DataBaseModel.Instance.RetriveLeaderBoard(result =>
{
JsonLeaderBoardResult = result; //gets the data
if (callback != null)
callback(JsonLeaderBoardResult);
});
}
用法:
GetStoredHighScores((result) =>
{
Debug.Log(result);
});
编辑:
太好了,但是在 Action 之外的 `GetStoredHighScores' 中获得结果后仍然需要做一些事情,否则我会得到这样的错误:get_transform 只能从主线程调用。
您收到此错误是因为RetriveLeaderBoard
它正在另一个线程上运行。UnityThread
从这篇文章中抓取,然后使用UnityThread.executeInUpdate
.
您的新代码:
void Awake()
{
UnityThread.initUnityThread();
}
private void GetStoredHighScores(Action<string> callback)
{
string JsonLeaderBoardResult;
DataBaseModel.Instance.RetriveLeaderBoard(result =>
{
JsonLeaderBoardResult = result; //gets the data
UnityThread.executeInUpdate(() =>
{
if (callback != null)
callback(JsonLeaderBoardResult);
});
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句