您可以使用 Firebase Authentication 允許使用者透過一或多種登入方式登入遊戲,包括電子郵件地址和密碼登入,以及 Google 登入和 Facebook 登入等聯合身分識別提供者。本教學課程將帶您瞭解如何開始使用 Firebase Authentication,並說明如何在遊戲中加入電子郵件地址和密碼登入功能。
事前準備
如要使用 Firebase Authentication, 請先完成下列步驟:
註冊 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.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) {
Debug.Log("Signed out " + user.UserId);
}
user = auth.CurrentUser;
if (signedIn) {
Debug.Log("Signed in " + user.UserId);
displayName = user.DisplayName ?? "";
emailAddress = user.Email ?? "";
photoUrl = user.PhotoUrl ?? "";
}
}
}
void OnDestroy() {
auth.StateChanged -= AuthStateChanged;
auth = null;
}
後續步驟
瞭解如何新增其他身分識別提供者和匿名訪客帳戶的支援功能: