Firebase登录注册代码报CS0029错误:无法隐式转换Task<AuthResult>为FirebaseUser
解决Firebase Auth登录注册的CS0029类型转换错误
这个错误的核心原因是:你调用的SignInWithEmailAndPasswordAsync和CreateUserWithEmailAndPasswordAsync都是异步方法,它们返回的是Task<AuthResult>类型的对象,而不是直接的FirebaseUser。你直接把task赋值给FirebaseUser变量,自然会出现类型不匹配的编译错误。
修复步骤
只需要在获取用户对象时,先通过task.Result拿到AuthResult实例,再访问它的User属性就能得到FirebaseUser对象。
修改后的完整代码
public void OnClickSignIn() { FirebaseAuth auth = FirebaseAuth.DefaultInstance; Debug.Log("点击了登录按钮"); string emailText = emailSignin.GetComponent<TMP_InputField>().text; string passwordText = passwordSignin.GetComponent<TMP_InputField>().text; auth.SignInWithEmailAndPasswordAsync(emailText, passwordText).ContinueWithOnMainThread(task => { if (task.IsCanceled) { Debug.Log("登录已取消"); Debug.LogError("SignInWithEmailAndPasswordAsync已被取消。"); return; } if (task.IsFaulted) { Debug.Log("登录失败"); Debug.LogError("SignInWithEmailAndPasswordAsync遇到错误: " + task.Exception); signinFailNotification.OpenNotification(); return; } // 修复:从task.Result.User获取FirebaseUser FirebaseUser newUser = task.Result.User; if (newUser != null) { signinSuccessNotification.OpenNotification(); Debug.LogFormat("用户登录成功: {0} ({1})", newUser.DisplayName, newUser.UserId); } }); } public void OnClickSignUp() { FirebaseAuth auth = FirebaseAuth.DefaultInstance; Debug.Log("点击了注册按钮"); string emailText = emailSignup.GetComponent<TMP_InputField>().text; string passwordText = passwordSignup.GetComponent<TMP_InputField>().text; auth.CreateUserWithEmailAndPasswordAsync(emailText, passwordText) .ContinueWithOnMainThread(task => { if (task.IsCanceled) { Debug.Log("注册已取消"); Debug.LogError("CreateUserWithEmailAndPasswordAsync已被取消。"); return; } if (task.IsFaulted) { Debug.Log("注册失败"); Debug.LogError("CreateUserWithEmailAndPasswordAsync遇到错误: " + task.Exception); signupFailNotification.OpenNotification(); return; } // Firebase用户已创建 Debug.Log("注册成功"); // 修复:从task.Result.User获取FirebaseUser FirebaseUser newUser = task.Result.User; if (newUser != null) { writeNewUser(newUser.UserId, newUser.Email); signupSuccessNotification.OpenNotification(); Debug.LogFormat("Firebase用户创建成功: {0} ({1})", newUser.DisplayName, newUser.UserId); } }); }
关键修改点
- 登录方法中:把
FirebaseUser newUser = task;改成FirebaseUser newUser = task.Result.User; - 注册方法中:同样把
FirebaseUser newUser = task;改成FirebaseUser newUser = task.Result.User;
内容的提问来源于stack exchange,提问作者M. Fahrurreza
相关产品推荐
相关产品推荐

