Home>

Currently I want to create a process to read and write reusable data using Firebase in Unity.
As for writing, it was written asynchronously and finished.

I want to continue processing after loading, but I don't know how to make the code reusable because the data loading is asynchronous.

The code for receiving data in firebase is as follows.

FirebaseDatabase.DefaultInstance
      .GetReference ("Leaders")
      .GetValueAsync (). ContinueWith (task =&gt {
        if (task.IsFaulted) {
         }
        else if (task.IsCompleted) {
          DataSnapshot snapshot = task.Result;
        }
      });

I was thinking of functionalizing this code, but because it was asynchronous, I couldn't return when the data entered the snapshot variable.

How should we handle this process reusably?

  • Answer # 1

    Is it easy to use Action?
    [Unity] [C #] Callback implementation method in UnityEvent, Action, delegate, interface and registration in the inspector-blog | ∵ | ゝ (Fantom) development blog?
    Below is an example.

    using System;
    // ↑ required
    // Specify completion method when loading is executed
    void Start () {
        LoadFirebase (LoadComplete);
    }
    // Method executed after loading
    void LoadComplete (DataSnapshot snap) {
        Debug.Log (snap);
    }
    // load
    // Take DataSnapshot as an argument for now, but change it as you like
    void LoadFirebase (Action<DataSnapshot>action) {
          FirebaseDatabase.DefaultInstance
          .GetReference ("Leaders")
          .GetValueAsync (). ContinueWith (task =&gt {
            if (task.IsFaulted) {
             }
            else if (task.IsCompleted) {
              DataSnapshot snapshot = task.Result;
              action (snapshot);// Execute the specified method here
            }
          });
    }