Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Can't store result from query from firebase in a var

Discussion in 'Leaderboards' started by tomlugin100, Jun 21, 2023.

  1. tomlugin100

    tomlugin100

    Joined:
    May 6, 2023
    Posts:
    61
    Hello Y'all! Thank you for reading my post! I'm trying to use Firebase to create a leaderboard for my game.
    Code (CSharp):
    1. void receiveFirestoreData()
    2.     {
    3.         Query allUsersQuery = db.Collection("Usernames");
    4.         allUsersQuery.GetSnapshotAsync().ContinueWithOnMainThread(task =>
    5.         {
    6.             QuerySnapshot allUsersQuerySnapshot = task.Result;
    7.             foreach (DocumentSnapshot documentSnapshot in allUsersQuerySnapshot.Documents)
    8.             {
    9.                 Debug.Log($"Document data for {0} document:"+ documentSnapshot.Id);
    10.                 Dictionary<string, object> userNamesAndScores = documentSnapshot.ToDictionary();
    11.                 foreach (KeyValuePair<string, object> pair in userNamesAndScores)
    12.                 {
    13.                    
    14.                     Debug.Log(pair.Key.ToString() + ", " + pair.Value.ToString());
    15.                     Debug.Log($"{0}: {1}"+ $"{ pair.Key}" + $"{(string)pair.Value}");
    16.                     userScores.Add(pair.Key.ToString(), pair.Value.ToString());
    17.                     Debug.Log("userscore example: " + userScores[pair.Key]);
    18.                    
    19.                    
    20.                 }
    21.  
    22.                 // Newline to separate entries
    23.                 //
    24.             }
    25.         });
    26.     }
    I have this function but I haven't been able to get the data retrieved from my firebase database saved to any variable outside this function. That's what userScores is - a dictionary that I was trying to save the key-value pairs from my database to. But the dictionary always is null and Debug.Log() only works where there is no userScores variables. Please help me! How can I make this code work.
     
  2. tomlugin100

    tomlugin100

    Joined:
    May 6, 2023
    Posts:
    61
    Reading around, I think perhaps it's a timing issue? the code gets executed before there are any data received? However, the Debug.Log does log key-value pairs so should I be able to put that into a var right away?
     
  3. tomlugin100

    tomlugin100

    Joined:
    May 6, 2023
    Posts:
    61
    I managed to figure out that I can assign information from the snapshot to a text variable outside the scope of the function. However, I cannot do the same with a dictionary