为什么字符串在Firebase中返回null

时间:2018-10-22 21:24:05

标签: c# firebase unity3d firebase-authentication

//Anom loggin
    auth.SignInAnonymouslyAsync().ContinueWith(task =>
    {
        if (task.IsCanceled)
        {
            Debug.LogError("SignInAnonymouslyAsync was canceled.");
            return;
        }
        if (task.IsFaulted)
        {
            Debug.LogError("SignInAnonymouslyAsync encountered an error: " + task.Exception);
            return;
        }

        Firebase.Auth.FirebaseUser newUser = task.Result;
        Debug.LogFormat("User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);

        userdataString = newUser.UserId;
        Debug.Log("userdatastring: " + userdataString);
    });

    Debug.Log("userdatastring out: " + userdataString);
}

当它离开匿名函数时,该值返回null,但在其中,如果它返回我需要获取的id,则知道如何获取字符串值吗?

1 个答案:

答案 0 :(得分:1)

该firebase函数是一个异步函数,这意味着直到异步函数完成(处于成功或失败状态),内部回调才会运行

这意味着您的调试日志实际上是在运行异步函数的回调之前运行的。

以下是您可以做的几种选择:

  1. 让Firebase异步函数在准备就绪时调用回调函数。

    public void DoAnonymousSignIn(){
        auth.SignInAnonymouslyAsync().ContinueWith(OnSignInDone);
    }
    
    private void OnSignInDone(Task<Firebase.Auth.FirebaseUser> task){
        if (task.IsCanceled){
            Debug.LogError("SignInAnonymouslyAsync was canceled.");
            return;
        }
    
        if (task.IsFaulted){
            Debug.LogError("SignInAnonymouslyAsync encountered an error: " + task.Exception);
            return;
        }
    
        Firebase.Auth.FirebaseUser newUser = task.Result;
        Debug.LogFormat("User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
    
        userdataString = newUser.UserId;
        Debug.Log("userdatastring: " + userdataString);
    }
    
  2. 通过内联处理回调而不是使用回调函数来保持它的状态,然后设置一个将其标记为就绪的变量或直接从中调用“ SignInDone”函数(例如SignInSuccess())和SignInFailed())

  3. 您还可以设置自己的回调事件,也可以从其他脚本中订阅它们:

    using System;
    
    public static Action OnSignInSuccess;
    

    然后在您的Firebase异步回调中执行以下操作:

        // ... within auth.SignInAnonymouslyAsync() callback
    
        Firebase.Auth.FirebaseUser newUser = task.Result;
        Debug.LogFormat("User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
    
        userdataString = newUser.UserId;
    
        if(OnSignInSuccess != null)
            OnSignInSuccess.Invoke();
    }
    

    然后其他脚本可以通过以下方式订阅和取消订阅此回调事件:

    void OnEnable(){
        YourScript.OnSignInSuccess += SignInSuccess;
    }
    
    void OnDisable(){
        YourScript.OnSignInSuccess -= SignInSuccess;
    }
    
    private void SignInSuccess(){
        Debug.Log("userdatastring: " + YourScript.staticInstance.userDataString);
    }