unity get firebase data s array code example
Example 1: unity get data from firebase
https://firebase.google.com/docs/unity/setup
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://YOURPROJECTNAME.firebaseio.com/");
DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
FirebaseDatabase.DefaultInstance.GetReference("DATABASENAME").GetValueAsync().ContinueWith(task => {
if (task.IsFaulted)
{
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
}
});
Example 2: how to go through child in firebase Unity
void InitializeFirebase() {
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl ("https://slol.firebaseio.com/");
FirebaseDatabase.DefaultInstance
.GetReference ("Products").OrderByChild ("category").EqualTo("livingroom")
.ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
if (e2.DatabaseError != null) {
Debug.LogError (e2.DatabaseError.Message);
}
if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0) {
foreach (var childSnapshot in e2.Snapshot.Children) {
var name = childSnapshot.Child ("name").Value.ToString ();
text.text = name.ToString();
Debug.Log(name.ToString());
}
}
};
}
Example 3: iterate though data in firebase unity
public void GetUsers(List<User> users)
{
FirebaseDatabase.DefaultInstance
.GetReference("users")
.GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted) {
Debug.Log("Error was:"+task.Exception.Message);
Debug.LogError("Error was:"+task.Result.Children);
}
else if (task.IsCompleted) {
DataSnapshot snapshot = task.Result;
foreach(DataSnapshot s in snapshot.Children){
IDictionary dictUsers = (IDictionary)s.Value;
Debug.Log(dictUsers["displayName"]);
}
UIManager.instance.ShowOtherUsers();
}
});
}