Unity 中的 Firebase 驗證入門

您可以使用 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.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;
}

下一步

了解如何新增對其他身分提供者和匿名訪客帳號的支援: