Search Unity

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

Discussion in 'Scripting' started by suheib_98, Jan 16, 2021.

  1. suheib_98

    suheib_98

    Joined:
    Jan 15, 2021
    Posts:
    2
    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+<UpdateUsernameAuth>

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

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

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

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


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

    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3. using Firebase;
    4. using Firebase.Auth;
    5. using Firebase.Database;
    6. using TMPro;
    7.  
    8.  
    9.  
    10. public class FirebaseManager : MonoBehaviour
    11. {
    12.    public static FirebaseManager instance;
    13.     //Firebase variables
    14.     [Header("Firebase")]
    15.     public DependencyStatus dependencyStatus;
    16.     public FirebaseAuth auth;
    17.     public FirebaseUser User;
    18.     public DatabaseReference DBreference;
    19.     //Login variables
    20.     [Header("Login")]
    21.     public TMP_InputField emailLoginField;
    22.     public TMP_InputField passwordLoginField;
    23.     public TMP_Text warningLoginText;
    24.     public TMP_Text confirmLoginText;
    25.  
    26.     //Register variables
    27.     [Header("Register")]
    28.     public TMP_InputField emailRegisterField;
    29.     public TMP_InputField usernameRegisterField;
    30.     public TMP_InputField passwordRegisterField;
    31.  
    32.     public TMP_Text warningRegisterText;
    33.  
    34.     [Header("UserData")]
    35.  
    36.     public TMP_Text Coins;
    37.     public TMP_Text Diamond;
    38.     public TMP_Text LevelUp;
    39.  
    40.  
    41.  
    42.  
    43.  
    44.  
    45.  
    46.     void Awake()
    47.     {
    48.  
    49.         if (instance == null)
    50.         {
    51.             instance = this;
    52.         }
    53.         else if (instance != null)
    54.         {
    55.             Debug.Log("Instance already exists, destroying object!");
    56.             Destroy(this);
    57.         }
    58.  
    59.  
    60.     //Check that all of the necessary dependencies for Firebase are present on the system
    61.     FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
    62.         {
    63.             dependencyStatus = task.Result;
    64.             if (dependencyStatus == DependencyStatus.Available)
    65.             {
    66.            
    67.                 //If they are avalible Initialize Firebase
    68.                 InitializeFirebase();
    69.          
    70.             }
    71.             else
    72.             {
    73.                 Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
    74.             }
    75.         });
    76.  
    77.    
    78.     }
    79.  
    80.     private void Start()
    81.     {
    82.  
    83.         if (PlayerPrefs.GetString("isLoggedin") == "true")
    84.         {
    85.             UIManager.instance.Back();
    86.         }
    87.     }
    88.  
    89.     private void InitializeFirebase()
    90.     {
    91.         Debug.Log("Setting up Firebase Auth");
    92.         //Set the authentication instance object
    93.         auth = FirebaseAuth.DefaultInstance;
    94.         DBreference = FirebaseDatabase.DefaultInstance.RootReference;
    95.  
    96.  
    97.     }
    98.     public void ClearLoginFeilds()
    99.     {
    100.         emailLoginField.text = "";
    101.         passwordLoginField.text = "";
    102.     }
    103.     public void ClearRegisterFeilds()
    104.     {
    105.         emailRegisterField.text = "";
    106.         usernameRegisterField.text = "";
    107.         passwordRegisterField.text = "";
    108.    
    109.     }
    110.  
    111.     //Function for the login button
    112.     public void LoginButton()
    113.     {
    114.  
    115.             //Call the login coroutine passing the email and password
    116.             StartCoroutine(Login(emailLoginField.text, passwordLoginField.text));
    117.    
    118.     }
    119.     //Function for the register button
    120.     public void RegisterButton()
    121.     {
    122.    
    123.             //Call the register coroutine passing the email, password, and username
    124.             StartCoroutine(Register(emailRegisterField.text, passwordRegisterField.text, usernameRegisterField.text));
    125.    
    126.     }
    127.  
    128.     //Function for the sign out button
    129.  
    130. public void SignOutButton()
    131.     {
    132.      
    133.         StartCoroutine(UpdateUsernameAuth(PlayerPrefs.GetString("UserName")));
    134.         StartCoroutine(UpdateUsernameDatabase(PlayerPrefs.GetString("UserName")));
    135.  
    136.  
    137.         SaveCoins();
    138.         SaveDiamond();
    139.         SaveLevel();
    140.         SaveSocreNextLevel();
    141.  
    142.  
    143.         auth.SignOut();    
    144.         UIManager.instance.LoginScreen();
    145.         ClearRegisterFeilds();
    146.         ClearLoginFeilds();
    147.         PlayerPrefs.DeleteAll();
    148.         PlayerPrefs.Save();
    149.         Debug.Log("Status: Loggeout");
    150.         //StopAllCoroutines();
    151.     }
    152.    private void SaveCoins()
    153.     {
    154.         int temp = PlayerPrefs.GetInt("Coins");
    155.         StartCoroutine(UpdateCoins(temp));
    156.     }
    157.     private void SaveDiamond()
    158.     {
    159.         int temp = PlayerPrefs.GetInt("Diamond");
    160.         StartCoroutine(UpdateDiamond(temp));
    161.     }
    162.     private void SaveLevel()
    163.     {
    164.         int tmep = PlayerPrefs.GetInt("Level");
    165.         StartCoroutine(UpdateLevelUp(tmep));
    166.     }
    167.  
    168.  
    169.  
    170.  
    171.     private IEnumerator Login(string _email, string _password)
    172.     {
    173.         //Call the Firebase auth signin function passing the email and password
    174.         var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
    175.         //Wait until the task completes
    176.         yield return new WaitUntil(predicate: () => LoginTask.IsCompleted);
    177.  
    178.         if (LoginTask.Exception != null)
    179.         {
    180.             //If there are errors handle them
    181.             Debug.LogWarning(message: $"Failed to register task with {LoginTask.Exception}");
    182.             FirebaseException firebaseEx = LoginTask.Exception.GetBaseException() as FirebaseException;
    183.             AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
    184.  
    185.             string message = "Login Failed!";
    186.             switch (errorCode)
    187.             {
    188.                 case AuthError.MissingEmail:
    189.                     message = "Missing Email";
    190.                     break;
    191.                 case AuthError.MissingPassword:
    192.                     message = "Missing Password";
    193.                     break;
    194.                 case AuthError.WrongPassword:
    195.                     message = "Wrong Password";
    196.                     break;
    197.                 case AuthError.InvalidEmail:
    198.                     message = "Invalid Email";
    199.                     break;
    200.                 case AuthError.UserNotFound:
    201.                     message = "Account does not exist";
    202.                     break;
    203.             }
    204.             warningLoginText.text = message;
    205.         }
    206.         else
    207.         {
    208.             //User is now logged in
    209.             //Now get the result
    210.        
    211.             User = LoginTask.Result;
    212.             Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
    213.             warningLoginText.text = "";
    214.             confirmLoginText.text = "Logged In";      
    215.             StartCoroutine(LoadUserData());
    216.  
    217.             yield return new WaitForSeconds(2);
    218.  
    219.  
    220.             PlayerPrefs.SetString("isLoggedin", "true");
    221.             PlayerPrefs.SetString("UserName", User.DisplayName);
    222.             Debug.Log("Status: " + "Loggedin");
    223.             UIManager.instance.UserDataScreen();
    224.             confirmLoginText.text = "";
    225.             ClearLoginFeilds();
    226.             ClearRegisterFeilds();
    227.         }
    228.     }
    229.  
    230.     private IEnumerator Register(string _email, string _password, string _username)
    231.     {
    232.         if (_username == "")
    233.         {
    234.             //If the username field is blank show a warning
    235.             warningRegisterText.text = "Missing Username";
    236.         }
    237.  
    238.         else
    239.         {
    240.             //Call the Firebase auth signin function passing the email and password
    241.             var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);
    242.             //Wait until the task completes
    243.             yield return new WaitUntil(predicate: () => RegisterTask.IsCompleted);
    244.  
    245.             if (RegisterTask.Exception != null)
    246.             {
    247.                 //If there are errors handle them
    248.                 Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
    249.                 FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
    250.                 AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
    251.  
    252.                 string message = "Register Failed!";
    253.                 switch (errorCode)
    254.                 {
    255.                     case AuthError.MissingEmail:
    256.                         message = "Missing Email";
    257.                         break;
    258.                     case AuthError.MissingPassword:
    259.                         message = "Missing Password";
    260.                         break;
    261.                     case AuthError.WeakPassword:
    262.                         message = "Weak Password";
    263.                         break;
    264.                     case AuthError.EmailAlreadyInUse:
    265.                         message = "Email Already In Use";
    266.                         break;
    267.                 }
    268.                 warningRegisterText.text = message;
    269.             }
    270.             else
    271.             {
    272.                 //User has now been created
    273.                 //Now get the result
    274.                 User = RegisterTask.Result;
    275.  
    276.                 if (User != null)
    277.                 {
    278.                     //Create a user profile and set the username
    279.                     UserProfile profile = new UserProfile { DisplayName = _username };
    280.  
    281.                     //Call the Firebase auth update user profile function passing the profile with the username
    282.                     var ProfileTask = User.UpdateUserProfileAsync(profile);
    283.                     //Wait until the task completes
    284.                     yield return new WaitUntil(predicate: () => ProfileTask.IsCompleted);
    285.  
    286.                     if (ProfileTask.Exception != null)
    287.                     {
    288.                         //If there are errors handle them
    289.                         //If there are errors handle them
    290.                         Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
    291.                         warningRegisterText.text = "Username Set Failed!";
    292.                     }
    293.                     else
    294.                     {
    295.                         //Username is now set
    296.                         //Now return to login screen
    297.                         UIManager.instance.LoginScreen();
    298.                         warningRegisterText.text = "";
    299.                         ClearRegisterFeilds();
    300.                         ClearLoginFeilds();
    301.                     }
    302.                 }
    303.             }
    304.         }
    305.     }
    306.  
    307.     private IEnumerator UpdateUsernameAuth(string _username)
    308.     {
    309.         //Create a user profile and set the username
    310.         UserProfile profile = new UserProfile { DisplayName = _username };
    311.    
    312.         //Call the Firebase auth update user profile function passing the profile with the username
    313.         var ProfileTask = User.UpdateUserProfileAsync(profile);
    314.         //Wait until the task completes
    315.         yield return new WaitUntil(predicate: () => ProfileTask.IsCompleted);
    316.  
    317.         if (ProfileTask.Exception != null)
    318.         {
    319.             Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
    320.         }
    321.         else
    322.         {
    323.             //Auth username is now updated
    324.         }
    325.     }
    326.  
    327.     private IEnumerator UpdateUsernameDatabase(string _username)
    328.     {
    329.         //Set the currently logged in user username in the database
    330.         var DBTask = DBreference.Child("users").Child(User.UserId).Child("username").SetValueAsync(_username);
    331.         PlayerPrefs.SetString("UserName", _username);
    332.         yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
    333.  
    334.         if (DBTask.Exception != null)
    335.         {
    336.             Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
    337.         }
    338.         else
    339.         {
    340.             //Database username is now updated
    341.         }
    342.     }
    343.  
    344.     private IEnumerator UpdateCoins(int _coins)
    345.     {
    346.  
    347.         //Set the currently logged in user xp
    348.         var DBTask = DBreference.Child("users").Child(User.UserId).Child("coins").SetValueAsync(_coins);
    349.  
    350.         yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
    351.  
    352.         if (DBTask.Exception != null)
    353.         {
    354.             Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
    355.         }
    356.         else
    357.         {
    358.             //Xp is now updated
    359.             Debug.Log("The Coins Updated");
    360.         }
    361.     }
    362.  
    363.     private IEnumerator UpdateDiamond(int _diamond)
    364.     {
    365.    
    366.         //Set the currently logged in user kills
    367.         var DBTask = DBreference.Child("users").Child(User.UserId).Child("diamond").SetValueAsync(_diamond);
    368.  
    369.         yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
    370.  
    371.         if (DBTask.Exception != null)
    372.         {
    373.             Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
    374.         }
    375.         else
    376.         {
    377.             //Kills are now updated
    378.             Debug.Log("The diamond Updated");
    379.         }
    380.     }
    381.  
    382.     private IEnumerator UpdateLevelUp(int _levelup)
    383.  
    384.     {
    385.    
    386.         //Set the currently logged in user deaths
    387.         var DBTask = DBreference.Child("users").Child(User.UserId).Child("levelup").SetValueAsync(_levelup);
    388.  
    389.         yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
    390.  
    391.         if (DBTask.Exception != null)
    392.         {
    393.             Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
    394.         }
    395.         else
    396.         {
    397.             //Deaths are now updated
    398.             Debug.Log("The levelup Updated");
    399.         }
    400.     }
    401.  
    402.     private  IEnumerator LoadUserData()
    403.     {
    404.    
    405.         //Get the currently logged in user data
    406.         var DBTask =  DBreference.Child("users").Child(User.UserId).GetValueAsync();
    407.  
    408.         yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
    409.  
    410.         if (DBTask.Exception != null)
    411.         {
    412.             Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
    413.         }
    414.         else if (DBTask.Result.Value == null)
    415.         {
    416.             //No data exists yet
    417.             Coins.text = "0";
    418.             Diamond.text = "0";
    419.             LevelUp.text = "0";
    420.  
    421.             PlayerPrefs.SetInt("Coins", 0);
    422.             PlayerPrefs.SetInt("Diamond", 0);
    423.             PlayerPrefs.SetInt("Level", 0);
    424.         }
    425.         else
    426.         {
    427.             Debug.Log("SUheib");
    428.             //Data has been retrieved
    429.             DataSnapshot snapshot = DBTask.Result;
    430.        
    431.             Coins.text = snapshot.Child("coins").Value.ToString();
    432.             Diamond.text = snapshot.Child("diamond").Value.ToString();
    433.             LevelUp.text = snapshot.Child("levelup").Value.ToString();
    434.  
    435.             PlayerPrefs.SetInt("Coins", int.Parse(Coins.text));
    436.             PlayerPrefs.SetInt("Diamond", int.Parse(Diamond.text));
    437.             PlayerPrefs.SetInt("Level", int.Parse(LevelUp.text));
    438.         }
    439.     }
    440.  
    441. }
    442.  
     
    Last edited: Jan 16, 2021
  2. Stevens-R-Miller

    Stevens-R-Miller

    Joined:
    Oct 20, 2017
    Posts:
    676
    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.)
     
    Last edited: Jan 17, 2021
    PraetorBlue likes this.
  3. suheib_98

    suheib_98

    Joined:
    Jan 15, 2021
    Posts:
    2
    Sorry, this is the first time I post here :)

    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+<UpdateUsernameAuth>

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

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

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

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




    In this I need when exit from game push the data on Firebase From Line 130
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    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:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

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