Unity集成Firebase登录无响应求助(注册功能正常)
Hey there! Let's break down the issues in your login code that's causing the lack of feedback and wonky behavior:
1. Broken Logic in the Update() Method
- First, your focus-switch code is busted: when the email input is focused, you immediately select the password input. That means users can't even type their email!
- The condition
if (Password != ""&&Password != "")is a typo (you checkPasswordtwice instead ofEmailandPassword), and worse—this triggersLoginButton()every single frame as long as the password isn't empty. That's spamming login requests nonstop, which will cause all sorts of unexpected issues.
2. Missing Main Thread Execution for Unity Operations
Firebase's ContinueWith runs on a background thread by default. Unity doesn't let you modify UI or load scenes from non-main threads, so your success scene load might not fire properly, and any feedback you add won't show up for users.
3. Wrong Scene Loaded on Success
You're loading LoginScreen after a successful login—that's the login page itself! You should load your post-login scene (like MainMenu or HomeScreen instead).
4. No User-Visible Feedback
Right now you only have Debug.Log messages, which only show up in the editor console. Players won't see any success or error messages in-game.
Fixed Code Example
Here's the corrected version with all issues addressed:
using UnityEngine; using UnityEngine.UI; using Firebase.Auth; using UnityEngine.SceneManagement; public class Login : MonoBehaviour { public GameObject emailInput; public GameObject passwordInput; public Text feedbackText; // Add a Text UI element in your scene and assign this in Inspector private string _email; private string _password; private FirebaseAuth _auth; void Awake() { _auth = FirebaseAuth.DefaultInstance; // Hide feedback text when the scene starts if (feedbackText != null) feedbackText.gameObject.SetActive(false); } void Update () { // Update input values every frame (no broken focus logic anymore) _email = emailInput.GetComponent<InputField>().text; _password = passwordInput.GetComponent<InputField>().text; } public void LoginButton() { // Validate input before sending a request if (string.IsNullOrEmpty(_email) || string.IsNullOrEmpty(_password)) { ShowFeedback("Please enter both email and password!", Color.red); return; } // Use ContinueWithOnMainThread to ensure Unity operations run on the right thread _auth.SignInWithEmailAndPasswordAsync(_email, _password).ContinueWithOnMainThread(task => { if (task.IsCanceled) { ShowFeedback("Login canceled. Please try again.", Color.red); Debug.LogError("SignInWithEmailAndPasswordAsync was canceled."); return; } if (task.IsFaulted) { // Translate Firebase error codes to user-friendly messages string errorMessage = "Login failed. Please check your credentials."; foreach (var exception in task.Exception.InnerExceptions) { FirebaseException firebaseEx = exception as FirebaseException; if (firebaseEx != null) { AuthError errorCode = (AuthError)firebaseEx.ErrorCode; errorMessage = GetAuthErrorMessage(errorCode); } } ShowFeedback(errorMessage, Color.red); Debug.LogError("SignInWithEmailAndPasswordAsync error: " + task.Exception); return; } // Login success! FirebaseUser newUser = task.Result; Debug.LogFormat("User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId); ShowFeedback("Login successful! Redirecting...", Color.green); // Load your actual post-login scene (replace with your scene name) SceneManager.LoadScene("MainMenu"); }); } private void ShowFeedback(string message, Color textColor) { if (feedbackText == null) return; feedbackText.text = message; feedbackText.color = textColor; feedbackText.gameObject.SetActive(true); // Optional: Hide feedback after 3 seconds Invoke(nameof(HideFeedback), 3f); } private void HideFeedback() { if (feedbackText != null) feedbackText.gameObject.SetActive(false); } // Helper to convert Firebase error codes to readable messages private string GetAuthErrorMessage(AuthError errorCode) { switch (errorCode) { case AuthError.UserNotFound: return "No account found with this email."; case AuthError.WrongPassword: return "Incorrect password."; case AuthError.InvalidEmail: return "Please enter a valid email address."; case AuthError.UserDisabled: return "This account has been disabled."; default: return "Login failed. Please try again later."; } } }
Key Fixes Explained
- Removed broken focus logic: Users can now type their email normally without being forced to the password field immediately.
- Added input validation: Checks if fields are empty before sending a login request, preventing unnecessary Firebase calls.
- Used
ContinueWithOnMainThread: Ensures all UI updates and scene loading run on Unity's main thread (this uses Firebase's built-in extension, included with the SDK). - Added user-facing feedback: Uses a Text UI element to show clear success/error messages players can see.
- Fixed scene load: Changed to load a post-login scene instead of looping back to the login screen.
- Improved error handling: Maps Firebase's technical error codes to plain-language messages users can understand.
Quick Setup Steps
- Add a
TextUI element to your login scene (position it below the login button so users can see it easily). - Drag this Text element into the
feedbackTextfield in the Login script's Inspector. - Replace
"MainMenu"with the actual name of your post-login scene (make sure it's added to your Build Settings!).
内容的提问来源于stack exchange,提问作者EmmaGrealy

