Unity 中的 Firebase 身份驗證入門

您可以使用 Firebase 身份驗證允許用戶使用一種或多種登錄方法登錄您的遊戲,包括電子郵件地址和密碼登錄,以及聯合身份提供商(例如 Google 登錄和 Facebook 登錄)。本教程通過向您展示如何向您的遊戲添加電子郵件地址和密碼登錄,幫助您開始使用 Firebase 身份驗證。

在你開始之前

在使用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) {
      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;
}

下一步

了解如何添加對其他身份提供者和匿名訪客帳戶的支持: