【问题标题】:Unity Firestore , get data convert to stringUnity Firestore,将数据转换为字符串
【发布时间】:2021-05-05 02:41:13
【问题描述】:

我对 c# 很陌生,我正在尝试将从 firestore 获得的数据保存到一个字符串中,我已经搜索并尝试了许多不同的东西,但似乎无法得到它,非常感谢任何帮助,这是我的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase;
using Firebase.Database;
using Firebase.Firestore;
using Firebase.Extensions;
using System;

public class FirestoreGet : MonoBehaviour
{
    public string Name;
    public string lastName;



    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Start");
        call();
    }

    async void call()
    {
        FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
        DocumentReference docRef = db.Collection("Test").Document("Test");
        DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
        if (snapshot.Exists)
        {
            Debug.LogFormat("Document data for {0} document:", snapshot.Id);
            Dictionary<string, object> data = snapshot.ToDictionary();
            foreach (KeyValuePair<string, object> pair in data)
            {
                Debug.LogFormat("{0}: {1}", pair.Key, pair.Value);
            }
        }
        else
        {
            Debug.LogFormat("Document {0} does not exist!", snapshot.Id);
        }
    }

}

【问题讨论】:

  • 你能分享你拥有的任何调试日志吗(为了方便,这应该可以在编辑器中运行)?确认一下,您的“文档”是否命名为Test,它是否也在名为Test 的“集合”中?如果 Firestore 控制台的屏幕截图不显示太多信息,它也会有所帮助。你是否也在做类似var dependencyStatus = await FirebaseApp.CheckAndFixDependenciesAsync() 的事情并等待它在这个脚本之外返回?
  • 是的,我的调试控制台返回数据,我只是不确定如何将它返回的数据转换成字符串

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


【解决方案1】:

如果我的理解是正确的,那么您的数据就在那里并且您正在记录它。你只需要一个 C# 中的字符串。有几种方法可以做到这一点。

最简单的就是这样做:

var strValue = (string)pair.Value;

如果该值不是字符串,您将获得一个您想要处理的InvalidCastException(数据来自互联网,您总是想要验证它)。 p>

为避免这种情况,您可以执行以下操作:

if (pair.Value is string) {
    var strValue = (string)pair.Value;
}

您也可以使用as 关键字,它不会引发异常,而是会导致值变为空:

var strValue = pair.Value as string;

最后,你可以使用.ToString() 方法,以防你有一个非字符串值并且你想要一个字符串。

var strValue = pair.Value.ToString();

如果您希望 pair.Value 转到 null(可能是个好主意),您可以使用空传播。请注意,这not work as expected 用于继承自UnityEngine.Object 的任何类型,因此不要将其散布在您的代码库中。

var strValue = pair.Value?.ToString() ?? "null";

稍后,如果您的数据变得更加结构化,您可以使用 Firestore 的built in serialization capabilities。这就是我在自己的游戏中通常与 Firestore 交互的方式:

[FirestoreData]
struct MyData {
    // get a string, to answer the question in the post
    [FirestoreProperty]
    public string StringValue { get; set; }

    // get an int to demonstrate that it's not string specific
    [FirestoreProperty]
    public int IntValue { get; set; }
}
docRef.GetSnapshotAsync().ContinueWithOnMainThread((task) => {
    var snapshot = task.Result;
    if (snapshot.Exists) {
        var myData = snapshot.ConvertTo<MyData>();
    }
});

【讨论】:

    猜你喜欢
    • 2022-11-09
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 2015-11-21
    • 2013-10-26
    • 2018-03-29
    相关资源
    最近更新 更多