首页 > 解决方案 > 如何通过 Unity SDK 将数组存储到 Firebase

问题描述

我正在尝试将 Int32[] 数组和 bool[] 数组存储到 Firebase,但它对我不起作用。我已经搜索了很多地方,但找不到解决方案。谁能告诉我,如何将数组从 Unity 存储到 Firebase 实时数据库。

System.Reflection用来获取类的所有公共静态字段UserPrefs

这是代码,我正在尝试做这项工作......

        System.Type type = typeof(UserPrefs);
        FieldInfo[] fields = type.GetFields();
        foreach (var field in fields) {
            if (user != null)    
        dbReference.Child("users").Child(user.UserId).Child(field.Name).SetValueAsync(field.GetValue(null));
            else
                    Debug.LogError("There is no user LoggedIn to write...");
        }

上面的代码保存了数组以外的所有值。数组上给出的错误如下:

InvalidCastException:无法从源类型转换为目标类型。Firebase.Database.Internal.Utilities.Validation.ValidateWritableObject(System.Object 对象)

任何帮助都感激不尽...

标签: arraysfirebaseunity3dfirebase-realtime-database

解决方案


你需要这样的课程。

public class MyClass
{
    public int[] intArray = new int[10];
}

然后你可以像这样将该对象写入 Firebase。

public void WriteArrays()
{
    MyClass temp = new MyClass();

    for (int i = 0; i < temp.intArray.Length; i++)
    {
        temp.intArray[i] = i;
    }

    databaseReference.Child("MyArrayNode").SetRawJsonValueAsync(JsonUtility.ToJson(temp));
}

databaseReference是对您的根目录的引用。

同样,您也可以为bool[]执行此操作。


推荐阅读