从 Firestore 检索数据时遇到问题

时间:2021-06-06 15:58:19

标签: c# firebase unity3d google-cloud-firestore

我是 firebase 的新手,我目前正在联合开发部落冲突克隆游戏项目。我需要将用户数据(例如建筑物放置详细信息、他们的 lvl 和其他个人资料详细信息)放入 Cloud Firestore。我可以将此详细信息存储到 cloud firestore。但是我在从中检索数据时遇到了麻烦。我不太了解 firestore,我查看了他们的文档和一些 youtube 视频以将数据保存到 firestore,但我无法检索。

DocumentReference docRef = db.Collection("cities").Document("SF");
docRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
{
  DocumentSnapshot snapshot = task.Result;
  if (snapshot.Exists) {
    Debug.Log(String.Format("Document data for {0} document:", snapshot.Id));
    Dictionary<string, object> city = snapshot.ToDictionary();
    foreach (KeyValuePair<string, object> pair in city) {
      Debug.Log(String.Format("{0}: {1}", pair.Key, pair.Value));
    }
  } else {
    Debug.Log(String.Format("Document {0} does not exist!", snapshot.Id));
  }
});

这不是我的代码,我是从他们的文档中得到的,我的代码与此类似。我可以调试数据。但是我不能在这个 lambda 表达式之外使用它。我需要将数据保存到变量并使用它,就像我需要获取建筑物放置详细信息(我是一个字符串列表)一样,并在用户玩游戏时使用它来放置建筑物。

1 个答案:

答案 0 :(得分:0)

就像@DedSec x47 所说的那样,您似乎遇到了更多的同步问题,而不是 firestore 问题。 要意识到的关键是您正在创建一个函数,该函数在 Firestore 检索您的数据时被称为 。 lambda 中的代码不会被立即调用,而是在主线程上检索数据时调用。问题不在于您从 lamda 外部访问结果,而是当您访问任务时,还没有从 firestore 检索到的结果。

我会研究 C# 中的 async/await 模式,它允许您以开发人员感觉是单线程的方式编写异步代码。我在 Firebase 项目中经常使用这种模式。

使用 async/await 上面的代码可能会变成:

DocumentReference docRef = db.Collection("cities").Document("SF");
DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
if (snapshot.Exists) 
{
    Debug.Log(String.Format("Document data for {0} document:", snapshot.Id));
    Dictionary<string, object> city = snapshot.ToDictionary();
    foreach (KeyValuePair<string, object> pair in city)
    Debug.Log(String.Format("{0}: {1}", pair.Key, pair.Value));
} 
else
    Debug.Log(String.Format("Document {0} does not exist!", snapshot.Id));

(尽管 outters 方法的签名必须更改为 async Task<myReturnType> myMethodName(myParams...),因此此代码在您的项目中无法按原样运行。

相关问题