在 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;
}
后续步骤
了解如何添加对其他身份提供方和匿名访客账号的支持:
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-08。
[null,null,["最后更新时间 (UTC):2025-08-08。"],[],[],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)"]]