Firebase Google 登录身份验证在 Unity 游戏中不起作用,并且 Google 登录用户未显示在 Firebase 实时数据库中

问题描述 投票:0回答:1

Firebase Google 登录身份验证在我的 Unity 游戏中不起作用,并且 Google 登录用户未显示在 Firebase 实时数据库中。单击 Google 登录按钮时,将调用 SignInWithGoogle() 方法,并在屏幕上的 infoText 位置显示“Calling SignIn”文本。但是,实际的 Google 登录并未发生,并且用户在 Firebase 控制台上不可见。尽管阅读了文档并确保我使用了正确的 Web 客户端 ID,但我似乎无法解决此问题。另外,我已经在 Firebase 的身份验证部分启用了 Google。请帮帮我。

下面是我的代码:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Firebase;
using Firebase.Auth;
using Google;
using UnityEngine;
using UnityEngine.UI;

public class GoogleSignInDemo : MonoBehaviour
{
    public Text infoText;
    public string webClientId = "aaaaaakaakaksjaaa.apps.googleusercontent.com";

    private FirebaseAuth auth;
    private GoogleSignInConfiguration configuration;

    public GameObject googleSignInButton, anonymousSignInButton;
    public GameObject logoutButton;

    private void Awake()
    {
        configuration = new GoogleSignInConfiguration { WebClientId = webClientId, RequestEmail = true, RequestIdToken = true };
        CheckFirebaseDependencies();
        CheckSignInStatus(); // Check sign-in status on awake
    }

    private void CheckSignInStatus()
    {
        if (auth.CurrentUser != null)
        {
            // User is already signed in
            googleSignInButton.SetActive(false);
            anonymousSignInButton.SetActive(false);
            logoutButton.SetActive(true);
            LoadGemsCountForCurrentUser();
        }
        else
        {
            // User is not signed in
            googleSignInButton.SetActive(true);
            anonymousSignInButton.SetActive(true);
            logoutButton.SetActive(false);
        }
    }

    private void LoadGemsCountForCurrentUser()
    {
        if (auth.CurrentUser != null)
        {
            // Load gems count for the current user from the cloud
            DiamondManager.instance.LoadGemsCountFromCloud();
        }
    }

    private void CheckFirebaseDependencies()
    {
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
        {
            if (task.IsCompleted)
            {
                if (task.Result == DependencyStatus.Available)
                    auth = FirebaseAuth.DefaultInstance;
                else
                    AddToInformation("Could not resolve all Firebase dependencies: " + task.Result.ToString());
            }
            else
            {
                AddToInformation("Dependency check was not completed. Error : " + task.Exception.Message);
            }
        });
    }

    public void SignInWithGoogle()
    {
        OnSignIn();
    }

    public void SignOutFromGoogle()
    {
        OnSignOut();
    }

    public void OnSignIn()
    {
        GoogleSignIn.Configuration = configuration;
        GoogleSignIn.Configuration.UseGameSignIn = false;
        GoogleSignIn.Configuration.RequestIdToken = true;
        AddToInformation("Calling SignIn");

        GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnAuthenticationFinished);
    }

    private void OnSignOut()
    {
        AddToInformation("Calling SignOut");
        GoogleSignIn.DefaultInstance.SignOut();

        auth.SignOut();

        googleSignInButton.SetActive(true);
        anonymousSignInButton.SetActive(true);
    }

    //handle the logout process for both Google and anonymous sign-ins
    public void SignOut()
    {
        if (GoogleSignIn.DefaultInstance != null)
        {
            GoogleSignIn.DefaultInstance.SignOut();
        }
        if (auth.CurrentUser != null)
        {
            auth.SignOut();
        }
        CheckSignInStatus(); // Update UI after sign-out
    }



    internal void OnAuthenticationFinished(Task<GoogleSignInUser> task)
    {
        if (task.IsFaulted)
        {
            using (IEnumerator<Exception> enumerator = task.Exception.InnerExceptions.GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    GoogleSignIn.SignInException error = (GoogleSignIn.SignInException)enumerator.Current;
                    AddToInformation("Got Error: " + error.Message);
                    Debug.Log(error);
                }
                else
                {
                    AddToInformation("Got Unexpected Exception?!?" + task.Exception);
                }
            }
        }
        else if (task.IsCanceled)
        {
            AddToInformation("Canceled");
        }
        else
        {
            googleSignInButton.SetActive(false);
            anonymousSignInButton.SetActive(false);
            AddToInformation("Welcome: " + task.Result.DisplayName + "!");
            AddToInformation("Email = " + task.Result.Email);
            AddToInformation("Google ID Token = " + task.Result.IdToken);
            AddToInformation("Email = " + task.Result.Email);
            SignInWithGoogleOnFirebase(task.Result.IdToken);
        }
    }

    private async Task SignInWithGoogleOnFirebase(string idToken)
    {
        if (string.IsNullOrEmpty(idToken))
        {
            AddToInformation("Google ID Token is null or empty.");
            return;
        }

        Credential credential = GoogleAuthProvider.GetCredential(idToken, null);

        await auth.SignInWithCredentialAsync(credential).ContinueWith(HandleLoginResult);

        await DiamondManager.instance.LoadGemsCountFromCloud();

    }

    private async void HandleLoginResult(Task<FirebaseUser> task)
    {
        if (task.IsCanceled)
        {
            Debug.LogError("SignInWithCredentialAsync was canceled.");
            return;
        }
        if (task.IsFaulted)
        {
            Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception.InnerException.Message);
            return;
        }

        FirebaseUser newUser = task.Result;
        Debug.Log($"User signed in successfully: {newUser.DisplayName} ({newUser.UserId})");
    }


    private List<string> messages = new List<string>();

    void AddToInformation(string text)
    {
        if (messages.Count == 5)
        {
            messages.RemoveAt(0);
        }
        messages.Add(text);
        string txt = "";
        foreach (string s in messages)
        {
            txt += "\n" + s;
        }
        infoText.text = txt;
    }


}

我需要 Google 登录才能工作,并且用户需要在 Firebase 控制台中显示。

c# firebase unity-game-engine firebase-realtime-database firebase-authentication
1个回答
0
投票

尝试更改具有任务的方法

ContinueWith

ContinueWithOnMainThread

您还应该移动“CheckSignInStatus();”进入“CheckFirebaseDependency”方法,以便它有机会在调用它之前完成。 Unity 中的 Firebase 有点棘手,您必须确保在主线程上运行。 抱歉,我没有 Unity Firebase 项目可供测试,但希望这会有所帮助。祝你好运:)

© www.soinside.com 2019 - 2024. All rights reserved.