開始在 Unity 中使用 Firebase 驗證
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
您可以使用 Firebase Authentication 允許使用者透過一或多種登入方式登入遊戲,包括電子郵件地址和密碼登入,以及 Google 登入和 Facebook 登入等聯合身分識別提供者。本教學課程將帶您瞭解如何開始使用 Firebase Authentication,並說明如何在遊戲中加入電子郵件地址和密碼登入功能。
事前準備
如要使用
Firebase Authentication,
請先完成下列步驟:
請注意,將 Firebase 新增至 Unity 專案時,您需要在Firebase控制台和開啟的 Unity 專案中執行工作 (例如從控制台下載 Firebase 設定檔,然後移至 Unity 專案)。
註冊新使用者
建立表單,讓新使用者透過電子郵件地址和密碼註冊遊戲。使用者填寫表單後,請驗證使用者提供的電子郵件地址和密碼,然後將這些資訊傳遞至 CreateUserWithEmailAndPasswordAsync
方法:
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// Firebase user has been created.
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("Firebase user created successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
});
登入現有使用者
建立表單,讓現有使用者可以透過電子郵件地址和密碼登入。使用者填寫完表單後,請呼叫 SignInWithEmailAndPasswordAsync
方法:
auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
});
設定驗證狀態變更事件處理常式並取得使用者資料
如要回應登入和登出事件,請將事件處理常式附加至全域驗證物件。每當使用者登入狀態變更時,系統就會呼叫這個處理常式。由於處理常式只會在驗證物件完全初始化後,以及所有網路呼叫完成後執行,因此這是取得已登入使用者資訊的最佳位置。
使用 FirebaseAuth
物件的 StateChanged
欄位註冊事件處理常式。使用者成功登入後,您可以在事件處理常式中取得使用者資訊。
最後,當這個物件呼叫 Destroy
時,系統會自動呼叫 OnDestroy
。在 OnDestroy
中清除 Auth 物件的參照。
void InitializeFirebase() {
auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.StateChanged += AuthStateChanged;
AuthStateChanged(this, null);
}
void AuthStateChanged(object sender, System.EventArgs eventArgs) {
if (auth.CurrentUser != user) {
bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null
&& auth.CurrentUser.IsValid();
if (!signedIn && user != null) {
DebugLog("Signed out " + user.UserId);
}
user = auth.CurrentUser;
if (signedIn) {
DebugLog("Signed in " + user.UserId);
displayName = user.DisplayName ?? "";
emailAddress = user.Email ?? "";
photoUrl = user.PhotoUrl ?? "";
}
}
}
void OnDestroy() {
auth.StateChanged -= AuthStateChanged;
auth = null;
}
後續步驟
瞭解如何新增其他身分識別提供者和匿名訪客帳戶的支援功能:
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-23 (世界標準時間)。
[null,null,["上次更新時間:2025-08-23 (世界標準時間)。"],[],[],null,["You can use Firebase Authentication to allow users to sign in to your game using one\nor more sign-in methods, including email address and password sign-in, and\nfederated identity providers such as Google Sign-in and Facebook Login. This\ntutorial gets you started with Firebase Authentication by showing you how to add\nemail address and password sign-in to your game.\n\nBefore you begin\n\nBefore you can use\n[Firebase Authentication](/docs/reference/unity/namespace/firebase/auth),\nyou need to:\n\n- Register your Unity project and configure it to use Firebase.\n\n - If your Unity project already uses Firebase, then it's already\n registered and configured for Firebase.\n\n - If you don't have a Unity project, you can download a\n [sample app](//github.com/google/mechahamster).\n\n- Add the [Firebase Unity SDK](/download/unity) (specifically, `FirebaseAuth.unitypackage`) to\n your Unity project.\n\n| **Find detailed instructions for these initial\n| setup tasks in\n| [Add Firebase to your Unity project](/docs/unity/setup#prerequisites).**\n\nNote that adding Firebase to your Unity project involves tasks both in the\n[Firebase console](//console.firebase.google.com/) and in your open Unity project\n(for example, you download Firebase config files from the console, then move\nthem into your Unity project).\n\nSign up new users\n\nCreate a form that allows new users to register with your game using their email\naddress and a password. When a user completes the form, validate the email\naddress and password provided by the user, then pass them to the\n`CreateUserWithEmailAndPasswordAsync` method: \n\n auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"CreateUserWithEmailAndPasswordAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\"CreateUserWithEmailAndPasswordAsync encountered an error: \" + task.Exception);\n return;\n }\n\n // Firebase user has been created.\n Firebase.Auth.AuthResult result = task.Result;\n Debug.LogFormat(\"Firebase user created successfully: {0} ({1})\",\n result.User.DisplayName, result.User.UserId);\n });\n\nSign in existing users\n\nCreate a form that allows existing users to sign in using their email address\nand password. When a user completes the form, call the\n`SignInWithEmailAndPasswordAsync` method: \n\n auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"SignInWithEmailAndPasswordAsync was canceled.\");\n return;\n }\n if (task.IsFaulted) {\n Debug.LogError(\"SignInWithEmailAndPasswordAsync encountered an error: \" + task.Exception);\n return;\n }\n\n Firebase.Auth.AuthResult result = task.Result;\n Debug.LogFormat(\"User signed in successfully: {0} ({1})\",\n result.User.DisplayName, result.User.UserId);\n });\n\nSet an authentication state change event handler and get user data\n\nTo respond to sign-in and sign-out events, attach an event handler to the global\nauthentication object. This handler gets called whenever the user's sign-in\nstate changes. Because the handler runs only after the authentication object is\nfully initialized and after any network calls have completed, it is the best\nplace to get information about the signed-in user.\n\nRegister the event handler using the `FirebaseAuth` object's `StateChanged`\nfield. When a user successfully signs in, you can get information about the user\nin the event handler.\n\nFinally, when this object has `Destroy` called on it, it will automatically call\n`OnDestroy`. Clean up the Auth object's references in `OnDestroy`. \n\n void InitializeFirebase() {\n auth = Firebase.Auth.FirebaseAuth.DefaultInstance;\n auth.StateChanged += AuthStateChanged;\n AuthStateChanged(this, null);\n }\n\n void AuthStateChanged(object sender, System.EventArgs eventArgs) {\n if (auth.CurrentUser != user) {\n bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null\n && auth.CurrentUser.IsValid();\n if (!signedIn && user != null) {\n DebugLog(\"Signed out \" + user.UserId);\n }\n user = auth.CurrentUser;\n if (signedIn) {\n DebugLog(\"Signed in \" + user.UserId);\n displayName = user.DisplayName ?? \"\";\n emailAddress = user.Email ?? \"\";\n photoUrl = user.PhotoUrl ?? \"\";\n }\n }\n }\n\n void OnDestroy() {\n auth.StateChanged -= AuthStateChanged;\n auth = null;\n }\n\nNext steps\n\nLearn how to add support for other identity providers and anonymous guest\naccounts:\n\n- [Google Sign-in](/docs/auth/unity/google-signin)\n- [Facebook Login](/docs/auth/unity/facebook-login)\n- [Twitter Login](/docs/auth/unity/twitter-login)\n- [GitHub Login](/docs/auth/unity/github-auth)\n- [Microsoft Login](/docs/auth/cpp/microsoft-oauth)\n- [Yahoo Login](/docs/auth/cpp/yahoo-oauth)\n- [Anonymous sign-in](/docs/auth/unity/anonymous-auth)\n- [Phone Authentication](/docs/auth/unity/phone-auth)"]]