您可以使用 Firebase 驗證,讓使用者透過一或多種登入方式 (包括電子郵件地址和密碼登入),以及 Google 登入和 Facebook 登入等聯合識別資訊提供者登入遊戲。本教學課程說明如何在遊戲中新增電子郵件地址和密碼登入程序,協助您開始使用 Firebase 驗證功能。
事前準備
使用 Firebase 驗證前,您必須先完成以下事項:
註冊 Unity 專案,並將其設定為使用 Firebase。
如果您的 Unity 專案已使用 Firebase,表示該專案已完成註冊並設定 Firebase。
如果您沒有 Unity 專案,可以下載範例應用程式。
在 Unity 專案中新增 Firebase Unity SDK (尤其是
FirebaseAuth.unitypackage
)。
請注意,將 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;
}
後續步驟
瞭解如何新增對其他識別資訊提供者和匿名訪客帳戶的支援: