How to get the children from Firebase Unity at once?

Viewed 314

I have following structure:

I used this code to get scores' children 0, 100, 900, 1000

public void GetRanking()
{
    FirebaseDatabase.DefaultInstance.GetReference("Ranking").ValueChanged += DatabaseManager_ValueChanged1;
}
private void DatabaseManager_ValueChanged1(object sender, ValueChangedEventArgs e)
{
    if (e != null)
    {
        print(e.Snapshot.Child("Scores").GetRawJsonValue());

    }
    else
    {
        GetRanking();
    }

}

I expected to get only that numbers (0, 100, 900, 1000), but result was

{"0":{"nName":"abc","uID":""},"100":{"nName":"abc","uID":""},"900":{"nName":"abc","uID":""}, "1000":{"nName":"abc","uID":""}}

Can you give me some suggestions?

2 Answers

Firebase always loads all data under the path that you call ValueChanged on, so the e.Snapshot has all data under Ranking.

If you only want to print the keys of the Scores, you can get the value of that snapshot, which gives you a Dictionary<String, object>, and then print the keys of the dictionary.

Something like:

print(e.Snapshot.Child("Scores").GetValue(false).Keys);

This was working, but there was a problem. I changed my scores as 50, 100, 500. However, result was 100, 50, 500. Sorting was not working because they were not number, so I putted them into list and then sorted.

public void GetRanking()                  
    {
        FirebaseDatabase.DefaultInstance.GetReference("Ranking").Child("Scores").OrderByKey().ValueChanged += DatabaseManager_ValueChanged1;

    }

    private void DatabaseManager_ValueChanged1(object sender, ValueChangedEventArgs e)
    {
        if (e != null)
        {
            
            foreach (var score in e.Snapshot.Children)
            {
                
                print("score: " + score.Key);
                                                                         
            }
            

        }

        else
        {
            GetRanking();                                                                                   
        }

    }
Related