I have read other posts about the same problem but they are not exactly same with my problem. I have created the bool flag to control if the asynchronous function is finished or not. Below snippet is what I am doing right now but the problem is because of while loop Unity freezes as if it never escape while loop but it should break while loop since waitFlag changes in the “getAllElementsAsync” method. Without while loop “getAllElements” method returns the value as null since it returns value before it is changed by “getAllElementsAsync” method. I am open to any other solutions that can solve my problem which is returning value after async method finishes. I have also tried creating coroutine for getAllElementsAsync method but it still returns value before coroutine finishes.
public class DatabaseConnection : MonoBehaviour {
private DataSnapshot dataSnapshot;
private bool waitFlag = true;
public Datasnapshot getAllElements(){
getAllElementsAsync();
while(this.waitFlag){}
return this.dataSnapshot
}
public void getAllElementsAsync(){
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("someURL");
DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
reference.GetValueAsync().ContinueWith(task => {
if (task.IsFaulted)
{
Debug.Log("not ok");
}
else if (task.IsCompleted)
{
Debug.Log("ok");
this.dataSnapshot = task.Result;
this.waitFlag = false;
}
});
}
}
I know coroutine is not async but I say startcoroutine is async. I tried to write getAllElements as coroutine then I called it with startcoroutine but it still returns value before coroutine finishes. I need to use this method from outside of this code so it needa to return value. Is there a way to return value from coroutine and assing it to parameter, like “var constant_value = startcoroutine(getallelements());”