NullReferenceException: Object reference not set to an instance of an object Firebase Manager

When I move to another scene to UpdateCoins(), UpdateDiamond() … It does not upload it to the database and it appears in console this Error

NullReferenceException: Object reference not set to an instance of an object
FirebaseManager+
NullReferenceException: Object reference not set to an instance of an object
FirebaseManager+
NullReferenceException: Object reference not set to an instance of an object FirebaseManager+
NullReferenceException: Object reference not set to an instance of an object
FirebaseManager+
NullReferenceException: Object reference not set to an instance of an object
FirebaseManager+

In this I need when exit from game push the data on Firebase From Line 130

using System.Collections;
using UnityEngine;
using Firebase;
using Firebase.Auth;
using Firebase.Database;
using TMPro;



public class FirebaseManager : MonoBehaviour
{
   public static FirebaseManager instance;
    //Firebase variables
    [Header("Firebase")]
    public DependencyStatus dependencyStatus;
    public FirebaseAuth auth;
    public FirebaseUser User;
    public DatabaseReference DBreference;
    //Login variables
    [Header("Login")]
    public TMP_InputField emailLoginField;
    public TMP_InputField passwordLoginField;
    public TMP_Text warningLoginText;
    public TMP_Text confirmLoginText;

    //Register variables
    [Header("Register")]
    public TMP_InputField emailRegisterField;
    public TMP_InputField usernameRegisterField;
    public TMP_InputField passwordRegisterField;
 
    public TMP_Text warningRegisterText;

    [Header("UserData")]
 
    public TMP_Text Coins;
    public TMP_Text Diamond;
    public TMP_Text LevelUp;
 

 


 

    void Awake()
    {

        if (instance == null)
        {
            instance = this;
        }
        else if (instance != null)
        {
            Debug.Log("Instance already exists, destroying object!");
            Destroy(this);
        }
 

    //Check that all of the necessary dependencies for Firebase are present on the system
    FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
        {
            dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
           
                //If they are avalible Initialize Firebase
                InitializeFirebase();
          
            }
            else
            {
                Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });

   
    }

    private void Start()
    {
  
        if (PlayerPrefs.GetString("isLoggedin") == "true")
        {
            UIManager.instance.Back();
        }
    }

    private void InitializeFirebase()
    {
        Debug.Log("Setting up Firebase Auth");
        //Set the authentication instance object
        auth = FirebaseAuth.DefaultInstance;
        DBreference = FirebaseDatabase.DefaultInstance.RootReference;
  

    }
    public void ClearLoginFeilds()
    {
        emailLoginField.text = "";
        passwordLoginField.text = "";
    }
    public void ClearRegisterFeilds()
    {
        emailRegisterField.text = "";
        usernameRegisterField.text = "";
        passwordRegisterField.text = "";
   
    }

    //Function for the login button
    public void LoginButton()
    {
  
            //Call the login coroutine passing the email and password
            StartCoroutine(Login(emailLoginField.text, passwordLoginField.text));
   
    }
    //Function for the register button
    public void RegisterButton()
    {
   
            //Call the register coroutine passing the email, password, and username
            StartCoroutine(Register(emailRegisterField.text, passwordRegisterField.text, usernameRegisterField.text));
   
    }

    //Function for the sign out button
 
public void SignOutButton()
    {
     
        StartCoroutine(UpdateUsernameAuth(PlayerPrefs.GetString("UserName")));
        StartCoroutine(UpdateUsernameDatabase(PlayerPrefs.GetString("UserName")));


        SaveCoins();
        SaveDiamond();
        SaveLevel();
        SaveSocreNextLevel();


        auth.SignOut();     
        UIManager.instance.LoginScreen();
        ClearRegisterFeilds();
        ClearLoginFeilds();
        PlayerPrefs.DeleteAll();
        PlayerPrefs.Save();
        Debug.Log("Status: Loggeout");
        //StopAllCoroutines();
    }
   private void SaveCoins()
    {
        int temp = PlayerPrefs.GetInt("Coins");
        StartCoroutine(UpdateCoins(temp));
    }
    private void SaveDiamond()
    {
        int temp = PlayerPrefs.GetInt("Diamond");
        StartCoroutine(UpdateDiamond(temp));
    }
    private void SaveLevel()
    {
        int tmep = PlayerPrefs.GetInt("Level");
        StartCoroutine(UpdateLevelUp(tmep));
    }




    private IEnumerator Login(string _email, string _password)
    {
        //Call the Firebase auth signin function passing the email and password
        var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
        //Wait until the task completes
        yield return new WaitUntil(predicate: () => LoginTask.IsCompleted);

        if (LoginTask.Exception != null)
        {
            //If there are errors handle them
            Debug.LogWarning(message: $"Failed to register task with {LoginTask.Exception}");
            FirebaseException firebaseEx = LoginTask.Exception.GetBaseException() as FirebaseException;
            AuthError errorCode = (AuthError)firebaseEx.ErrorCode;

            string message = "Login Failed!";
            switch (errorCode)
            {
                case AuthError.MissingEmail:
                    message = "Missing Email";
                    break;
                case AuthError.MissingPassword:
                    message = "Missing Password";
                    break;
                case AuthError.WrongPassword:
                    message = "Wrong Password";
                    break;
                case AuthError.InvalidEmail:
                    message = "Invalid Email";
                    break;
                case AuthError.UserNotFound:
                    message = "Account does not exist";
                    break;
            }
            warningLoginText.text = message;
        }
        else
        {
            //User is now logged in
            //Now get the result
       
            User = LoginTask.Result;
            Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
            warningLoginText.text = "";
            confirmLoginText.text = "Logged In";       
            StartCoroutine(LoadUserData());

            yield return new WaitForSeconds(2);


            PlayerPrefs.SetString("isLoggedin", "true");
            PlayerPrefs.SetString("UserName", User.DisplayName);
            Debug.Log("Status: " + "Loggedin");
            UIManager.instance.UserDataScreen();
            confirmLoginText.text = "";
            ClearLoginFeilds();
            ClearRegisterFeilds();
        }
    }

    private IEnumerator Register(string _email, string _password, string _username)
    {
        if (_username == "")
        {
            //If the username field is blank show a warning
            warningRegisterText.text = "Missing Username";
        }
 
        else
        {
            //Call the Firebase auth signin function passing the email and password
            var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);
            //Wait until the task completes
            yield return new WaitUntil(predicate: () => RegisterTask.IsCompleted);

            if (RegisterTask.Exception != null)
            {
                //If there are errors handle them
                Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
                FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
                AuthError errorCode = (AuthError)firebaseEx.ErrorCode;

                string message = "Register Failed!";
                switch (errorCode)
                {
                    case AuthError.MissingEmail:
                        message = "Missing Email";
                        break;
                    case AuthError.MissingPassword:
                        message = "Missing Password";
                        break;
                    case AuthError.WeakPassword:
                        message = "Weak Password";
                        break;
                    case AuthError.EmailAlreadyInUse:
                        message = "Email Already In Use";
                        break;
                }
                warningRegisterText.text = message;
            }
            else
            {
                //User has now been created
                //Now get the result
                User = RegisterTask.Result;

                if (User != null)
                {
                    //Create a user profile and set the username
                    UserProfile profile = new UserProfile { DisplayName = _username };

                    //Call the Firebase auth update user profile function passing the profile with the username
                    var ProfileTask = User.UpdateUserProfileAsync(profile);
                    //Wait until the task completes
                    yield return new WaitUntil(predicate: () => ProfileTask.IsCompleted);

                    if (ProfileTask.Exception != null)
                    {
                        //If there are errors handle them
                        //If there are errors handle them
                        Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
                        warningRegisterText.text = "Username Set Failed!";
                    }
                    else
                    {
                        //Username is now set
                        //Now return to login screen
                        UIManager.instance.LoginScreen();
                        warningRegisterText.text = "";
                        ClearRegisterFeilds();
                        ClearLoginFeilds();
                    }
                }
            }
        }
    }

    private IEnumerator UpdateUsernameAuth(string _username)
    {
        //Create a user profile and set the username
        UserProfile profile = new UserProfile { DisplayName = _username };
   
        //Call the Firebase auth update user profile function passing the profile with the username
        var ProfileTask = User.UpdateUserProfileAsync(profile);
        //Wait until the task completes
        yield return new WaitUntil(predicate: () => ProfileTask.IsCompleted);

        if (ProfileTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
        }
        else
        {
            //Auth username is now updated
        }
    }

    private IEnumerator UpdateUsernameDatabase(string _username)
    {
        //Set the currently logged in user username in the database
        var DBTask = DBreference.Child("users").Child(User.UserId).Child("username").SetValueAsync(_username);
        PlayerPrefs.SetString("UserName", _username);
        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
            //Database username is now updated
        }
    }

    private IEnumerator UpdateCoins(int _coins)
    {
  
        //Set the currently logged in user xp
        var DBTask = DBreference.Child("users").Child(User.UserId).Child("coins").SetValueAsync(_coins);

        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
            //Xp is now updated
            Debug.Log("The Coins Updated");
        }
    }

    private IEnumerator UpdateDiamond(int _diamond)
    {
   
        //Set the currently logged in user kills
        var DBTask = DBreference.Child("users").Child(User.UserId).Child("diamond").SetValueAsync(_diamond);

        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
            //Kills are now updated
            Debug.Log("The diamond Updated");
        }
    }

    private IEnumerator UpdateLevelUp(int _levelup)

    {
   
        //Set the currently logged in user deaths
        var DBTask = DBreference.Child("users").Child(User.UserId).Child("levelup").SetValueAsync(_levelup);

        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
            //Deaths are now updated
            Debug.Log("The levelup Updated");
        }
    }

    private  IEnumerator LoadUserData()
    {
   
        //Get the currently logged in user data
        var DBTask =  DBreference.Child("users").Child(User.UserId).GetValueAsync();
 
        yield return new WaitUntil(predicate: () => DBTask.IsCompleted);

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else if (DBTask.Result.Value == null)
        {
            //No data exists yet
            Coins.text = "0";
            Diamond.text = "0";
            LevelUp.text = "0";

            PlayerPrefs.SetInt("Coins", 0);
            PlayerPrefs.SetInt("Diamond", 0);
            PlayerPrefs.SetInt("Level", 0);
        }
        else
        {
            Debug.Log("SUheib");
            //Data has been retrieved
            DataSnapshot snapshot = DBTask.Result;
       
            Coins.text = snapshot.Child("coins").Value.ToString();
            Diamond.text = snapshot.Child("diamond").Value.ToString();
            LevelUp.text = snapshot.Child("levelup").Value.ToString();

            PlayerPrefs.SetInt("Coins", int.Parse(Coins.text));
            PlayerPrefs.SetInt("Diamond", int.Parse(Diamond.text));
            PlayerPrefs.SetInt("Level", int.Parse(LevelUp.text));
        }
    }

}

Welcome to the forums, suheib_98. When posting almost 500 lines of code, if you want help with an error it generates, you probably need to tell us which line number the error message is from.

(EDIT: In case anyone coming late thinks I’ve been harsh, suheib_98 originally posted only the code. The other text appeared after this post.)

1 Like

Sorry, this is the first time I post here :slight_smile:

The Problem is:
When I move to another scene to UpdateCoins(), UpdateDiamond() … It does not upload it to the database and it appears in console this Error

NullReferenceException: Object reference not set to an instance of an object
FirebaseManager+
NullReferenceException: Object reference not set to an instance of an object
FirebaseManager+
NullReferenceException: Object reference not set to an instance of an object FirebaseManager+
NullReferenceException: Object reference not set to an instance of an object
FirebaseManager+
NullReferenceException: Object reference not set to an instance of an object
FirebaseManager+

In this I need when exit from game push the data on Firebase From Line 130

The answer is always the same… ALWAYS. It is the single most common error ever. Don’t waste your life on this problem. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.