您可以使用Firebase身份驗證來允許用戶使用一種或多種登錄方法(包括電子郵件地址和密碼登錄)以及聯合身份提供商(例如Google登錄和Facebook登錄)登錄您的遊戲。本教程通過向您展示如何向遊戲中添加電子郵件地址和密碼登錄,使您開始使用Firebase身份驗證。
在你開始之前
在使用Firebase身份驗證之前,您需要:
註冊您的Unity項目並將其配置為使用Firebase。
如果您的Unity項目已經使用Firebase,則說明它已經為Firebase註冊並配置了。
如果您沒有Unity項目,則可以下載示例應用程序。
將Firebase Unity SDK (特別是
FirebaseAuth.unitypackage
)添加到您的Unity項目中。
請注意,將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.FirebaseUser newUser = task.Result;
Debug.LogFormat("Firebase user created successfully: {0} ({1})",
newUser.DisplayName, newUser.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.FirebaseUser newUser = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
});
設置身份驗證狀態更改事件處理程序並獲取用戶數據
要響應登錄和註銷事件,請將事件處理程序附加到全局身份驗證對象。每當用戶的登錄狀態更改時,都會調用此處理程序。因為處理程序僅在身份驗證對象完全初始化之後並且在完成任何網絡調用之後才運行,所以它是獲取有關已登錄用戶信息的最佳位置。
使用FirebaseAuth
對象的StateChanged
字段註冊事件處理程序。用戶成功登錄後,您可以在事件處理程序中獲取有關該用戶的信息。
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;
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 ?? "";
}
}
}
下一步
了解如何添加對其他身份提供者和匿名來賓帳戶的支持: