Question by 
               madferretdd · Oct 16, 2020 at 08:13 AM · 
                c#listdatabasegoogle  
              
 
              Firebase List Users
Hi, im new to using firebase and im struggling to create a list of users and their scores,
so far i have a register/login screen which works great and takes you to a new scene (gamescene), where there is a button which adds +1 to the database and also updates a Text gameobject with your username and score.
but it only brings up the username and score of who is logged in and i want it to show all usernames and scores in the database.
database: Game -Users --Dave ---Score:11 --Lee ---Score:19
 using System.Collections;
 using UnityEngine;
 
 using Firebase;
 using Firebase.Database;
 using Firebase.Unity.Editor;
 
 using Firebase.Auth;
 
 using TMPro;
 using UnityEngine.UI;
 using UnityEngine.SceneManagement;
 
 public class AuthManager : MonoBehaviour
 {
     //Firebase variables
     [Header("Firebase")]
     public DependencyStatus dependencyStatus;
     public FirebaseAuth auth;
     public FirebaseUser User;
     //DatabaseReference reference;
 
     //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 usernameRegisterField;
     public TMP_InputField emailRegisterField;
     public TMP_InputField passwordRegisterField;
     public TMP_InputField passwordRegisterVerifyField;
     public TMP_Text warningRegisterText;
     public Text LoadedText;
     DatabaseReference reference;
     public int Score = 0;
     private GameObject UIMan;
     //private FirebaseApp app;
 
     void Awake()
     {
         DontDestroyOnLoad(this.gameObject);
         Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
             dependencyStatus = task.Result;
             if (dependencyStatus == Firebase.DependencyStatus.Available)
             {
                 // Create and hold a reference to your FirebaseApp,
                 // where app is a Firebase.FirebaseApp property of your application class.
                 FirebaseApp app = Firebase.FirebaseApp.DefaultInstance;
 
                 // Set a flag here to indicate whether Firebase is ready to use by your app.
                 InitializeFirebase();
             }
             else
             {
                 Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
                 // Firebase Unity SDK is not safe to use here.
             }
         });
 
     }
 
     void Start()
     {
 
 
     }
 
 
 
     private void InitializeFirebase()
     {
         Debug.Log("Setting up Firebase Auth");
         //Set the authentication instance object
         auth = FirebaseAuth.DefaultInstance;
 
         FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("mydatabaseishere");
         
         reference = FirebaseDatabase.DefaultInstance.RootReference;
     }
 
     //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));
     }
 
     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";
             SceneManager.LoadScene(1);
 
             FirebaseDatabase.DefaultInstance.GetReference("Users").OrderByChild("Score").ValueChanged += AuthManager_ValueChanged;
         }
     }
 
     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 if (passwordRegisterField.text != passwordRegisterVerifyField.text)
         {
             //If the password does not match show a warning
             warningRegisterText.text = "Password Does Not Match!";
         }
         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
                         Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
                         FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
                         AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
                         warningRegisterText.text = "Username Set Failed!";
                     }
                     else
                     {
                         //Username is now set
                         //Now return to login screen
                         AuthUI.instance.LoginScreen();
                         warningRegisterText.text = "";
                         saveData();
                     }
                 }
             }
         }
     }
 
     public void Add()
     {
         Score++;
         reference.Child("Users").Child(User.DisplayName).Child("Score").SetValueAsync(Score);
         saveData();
     }
 
     public void saveData()
     { 
         reference.Child("Users").Child(User.DisplayName).Child("Score").SetValueAsync(Score);
         //reference.Child("Score").Child(User.).Child("_username").SetValueAsync(Score);
         
     }
 
     public void loadData()
     {
         
         //LoadedText = GetComponent<UIManager>().scoretxt;
         UIMan = GameObject.FindWithTag("UIMan");
         
         LoadedText = UIMan.GetComponent<UIManager>().scoretxt;
     }
 
     private void AuthManager_ValueChanged(object sender, ValueChangedEventArgs e)
     {
         if (e.DatabaseError != null)
         {
             Debug.LogError(e.DatabaseError.Message);
         }
 
         //LoadScore from database
         Score = int.Parse(e.Snapshot.Child(User.DisplayName).Child("Score").GetValue(true).ToString());
 
         if (e.Snapshot != null && e.Snapshot.ChildrenCount > 0)
         {
             //Show Results in a list
             foreach (var snapshot in e.Snapshot.Children)
             {
                 //var uname = e.Snapshot
                 var uname = e.Snapshot.Child("Users").Child(User.DisplayName).Key.ToString() + ": " + e.Snapshot.Child(User.DisplayName).Child("Score").GetValue(true).ToString();
                 LoadedText.text = uname.ToString();
 
             }
         }
     }
 }
               Comment
              
 
               
              Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                