首页 > 解决方案 > 将用户上传到 Firebase 实时数据库时出现 NullReferenceException

问题描述

尝试将新用户上传到 firebase 实时数据库时出现以下错误:

NullReferenceException: Object reference not set to an instance of an object
UserManager.UploadUserDatabase (User user, System.String userId) (at Assets/Scripts/UserManager.cs:34)
UploadUsers.OnAppStart () (at Assets/Scripts/UploadUsers.cs:40)

这是我在 UploadUsers 中传递的内容:

using UnityEngine;

public class UploadUsers : MonoBehaviour
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    private static void OnAppStart()
    {
        Debug.Log("On Load.");

        //User info
        var user3 = new User("Angel", "Doe", "Angeles", "Team3", "1234567", "fake3@gmail.com", "06/15/1994", "12bd3g");

        UserManager.UploadUserDatabase(user3, "12bd3g");
}

这是我尝试将用户上传到 Firebase 实时数据库的 UserManager 方法。第二个调试日志显示用户不为空:

public static void UploadUserDatabase(User user, string userId)
{
    Debug.Log("PostUserData method");
    Debug.Log("Data being passed: " + $"{user.firstNme} {user.lastNme} {user.userName} {user.team} {user.pswrd} {user.email} {user.team} {user.birthDate}");
    
    string json = JsonConvert.SerializeObject(user, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

    DBreference.Child("users").Child("profile").Child(userId).SetRawJsonValueAsync(json).ContinueWith(task =>
    {
        if (task.IsCompleted)
        {
            Debug.Log("successfully added user data to firebase");
        }
        else
        {
            Debug.Log("not successfull");
        }
    });
}

这是用户类:

using System;
using Newtonsoft.Json;

/// <summary>
/// The user class, which gets uploaded to the Firebase Database
/// </summary>

[Serializable] // This makes the class able to be serialized into a JSON
public class User
{
    public string firstNme;
    public string lastNme;
    public string userName;
    public string team;
    public string pswrd;
    public string email;
    public string birthDate;
    public string teamID;

    public User(string firstNme, string lastNme, string userName, string team, string pswrd, string email, string birthDate, string teamID)
    {
        this.firstNme = firstNme;
        this.lastNme = lastNme;
        this.userName = userName;
        this.team = team;
        this.pswrd = pswrd;
        this.email = email;
        this.birthDate = birthDate;
        this.teamID = teamID;
    }

    public User(){
    }
}

不知道我做错了什么。任何帮助表示赞赏。

标签: c#unity3dfirebase-realtime-database

解决方案


推荐阅读