首页 > 解决方案 > 在Unity / c#中向firebase发出请求后返回字符串

问题描述

有谁知道如何在完成后将 get 的值返回到 Firebase 数据库?例如,我想将字符串“extracted.pl_superhit”返回给另一个类,它是一个异步过程......

    public void LoadData_element(string player)
{

    FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
    FirebaseDatabase.DefaultInstance.GetReferenceFromUrl(DATA_URL).GetValueAsync()
        .ContinueWith((task =>
        {
            if (task.IsFaulted)
            {
                print("Falhou o Load dos dados");
            }
            if (task.IsCanceled)
            {
                print("Cancelou o load dos dados");
            }
            if (task.IsCompleted)
            {
                DataSnapshot datasnap = task.Result;
                string pData = datasnap.GetRawJsonValue();
                var humidval = datasnap.Child(player).GetRawJsonValue();
                string test = humidval.ToString();
                print("x:" + test);
                Firebase_Database_Player extracted = JsonUtility.FromJson<Firebase_Database_Player>(test);
                print("Player_name:" + extracted.pl_name);
                print("Player_lfbar:" + extracted.pl_lfbar);
                print("Player_hit:" + extracted.pl_hit);
                print("Player_superhit:" + extracted.pl_superhit);
                print("Player_defend:" + extracted.pl_defend);
                print("Player_atuallife:" + extracted.pl_atuallife);
                print("Player_atualattack:" + extracted.pl_atualattack);

            }

        }));


}

谢谢

标签: c#firebaseunity3dfirebase-realtime-database

解决方案


使函数异步并等待必要的调用

public async Task<string> LoadData_element(string player) {

    FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
    var reference = FirebaseDatabase.DefaultInstance.GetReferenceFromUrl(DATA_URL);
    DataSnapshot datasnap = await reference.GetValueAsync()

    string pData = datasnap.GetRawJsonValue();
    var humidval = datasnap.Child(player).GetRawJsonValue();
    string test = humidval.ToString();
    print("x:" + test);
    Firebase_Database_Player extracted = JsonUtility.FromJson<Firebase_Database_Player>(test);
    print("Player_name:" + extracted.pl_name);
    print("Player_lfbar:" + extracted.pl_lfbar);
    print("Player_hit:" + extracted.pl_hit);
    print("Player_superhit:" + extracted.pl_superhit);
    print("Player_defend:" + extracted.pl_defend);
    print("Player_atuallife:" + extracted.pl_atuallife);
    print("Player_atualattack:" + extracted.pl_atualattack);

    return extracted.pl_superhit;
}

推荐阅读