Jump to content
Unity Insider Forum

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


suheib98

Recommended Posts

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()
    {
 
     
         Debug.Log("Coins: " + PlayerPrefs.GetInt("Coins"));
         Debug.Log("Diamond: " + PlayerPrefs.GetInt("Diamond"));
         Debug.Log("Level: " + PlayerPrefs.GetInt("Level"));
         Debug.Log("Level: " + PlayerPrefs.GetString("UserName"));
 
        StartCoroutine(UpdateUsernameAuth(PlayerPrefs.GetString("UserName")));
        StartCoroutine(UpdateUsernameDatabase(PlayerPrefs.GetString("UserName")));
 
     
       
        StartCoroutine(UpdateCoins(PlayerPrefs.GetInt("Coins")));
        StartCoroutine(UpdateDiamond(PlayerPrefs.GetInt("Diamond")));
        StartCoroutine(UpdateLevelUp(PlayerPrefs.GetInt("Level")));
 
 
        auth.SignOut();      
        UIManager.instance.LoginScreen();
        ClearRegisterFeilds();
        ClearLoginFeilds();
        PlayerPrefs.DeleteAll();
        Debug.Log("Status: Loggeout");
     
 
    }
 
    public void SaveCoins()
    {
        StartCoroutine(UpdateUsernameAuth(PlayerPrefs.GetString("UserName")));
        StartCoroutine(UpdateUsernameDatabase(PlayerPrefs.GetString("UserName")));
 
        StartCoroutine(UpdateCoins(PlayerPrefs.GetInt("Coins")));
    }
 
    public void SaveDiamond()
    {
        StartCoroutine(UpdateUsernameAuth(PlayerPrefs.GetString("UserName")));
        StartCoroutine(UpdateUsernameDatabase(PlayerPrefs.GetString("UserName")));
 
        StartCoroutine(UpdateDiamond(PlayerPrefs.GetInt("Diamond")));
    }
 
    public void SaveLevel()
    {
        StartCoroutine(UpdateUsernameAuth(PlayerPrefs.GetString("UserName")));
        StartCoroutine(UpdateUsernameDatabase(PlayerPrefs.GetString("UserName")));
        StartCoroutine(UpdateLevelUp(PlayerPrefs.GetInt("Level")));
    }
    //Function for the save button
    public void SaveDataButton()
    {
     
    }
 
 
 
    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));
        }
    }
 
}

 

Link zu diesem Kommentar
Auf anderen Seiten teilen

Archiviert

Dieses Thema ist jetzt archiviert und für weitere Antworten gesperrt.

×
×
  • Neu erstellen...