YouCanCallMe Syarif
YouCanCallMe Syarif

Reputation: 169

Unity Editor wont connect to firebase auth

I'm here to make a game with anonymous login with firebase auth, and a database with firebase real-time database, everything works smoothly except for firebase auth. The problem is I don't know why? the unity won't connect to firebase auth.

Installation

I already install the package like always database and auth enter image description here

also for the firebase is like this enter image description here

Script

here my login script :

//Firebase variables
    [Header("Firebase")]
    public DependencyStatus dependencyStatus;
    public FirebaseAuth auth;
    public FirebaseUser User;
    public DatabaseReference DBreference;
    public static FirebaseManager instance;

    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
            instance = this;
        }

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
        {
            dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                InitializeFirebase();
            }
            else
            {
                Debug.LogError(
                    "Could not resolve all Firebase dependencies: " + dependency status);
            }
        });
    }

    public void InitializeFirebase()
    {
        auth = FirebaseAuth.DefaultInstance;
        DBreference = FirebaseDatabase.DefaultInstance.RootReference;
        auth.StateChanged += AuthStateChanged;
        AuthStateChanged(this, null);

    }

    void AuthStateChanged(object sender, System.EventArgs eventArgs)
    {
        //This checks if the user (your local user) is the same as the one from the auth
        if (auth.CurrentUser != User)
        {
            bool signedIn = User != auth.CurrentUser && auth.CurrentUser != null;
            User = auth.CurrentUser;
            if (signedIn)
            {
                Debug.Log("Signed in " + User.UserId + " " + User.DisplayName);
            }
            else
            {
                StartCoroutine(SignAnonymously());
            }
        }
    }

    //it does not directly log the user out but invalidates the auth
    void OnDestroy()
    {
        auth.StateChanged -= AuthStateChanged;
        auth = null;
    }

    public IEnumerator SignAnonymously()
    {
        var loginTask = auth.SignInAnonymouslyAsync();

        yield return new WaitUntil(predicate: () => loginTask.IsCompleted);

        if (loginTask.Exception != null)
        {
            //If there are errors handle them
            Debug.LogWarning(message: $"Failed to register task with {loginTask.Exception}");
        }
        else
        {
            User = loginTask.Result;
            Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.UserId);
        }
    }

What I've tried

note: I'm using unity ver 2020.3.1f1 LTS

am I doing it wrong?

Upvotes: 0

Views: 496

Answers (1)

Lotan
Lotan

Reputation: 4283

Try to replace your Coroutine method SignAnonymously with this async method:

public async void SignAnonymously()
{
   await auth.SignInAnonymouslyAsync().ContinueWith(task => {
      if (task.IsCanceled) {
        Debug.LogError("SignInAnonymouslyAsync was canceled.");
        return;
      }
      if (task.IsFaulted) {
        Debug.LogError("SignInAnonymouslyAsync encountered an error: " + task.Exception);
        return;
      }

      Firebase.Auth.FirebaseUser newUser = task.Result;
      Debug.LogFormat("User signed in successfully: {0} ({1})",
          newUser.DisplayName, newUser.UserId);
    });
}

I think that the problem could be the lacking of ContinueWithat the end of your SignInAnonymouslyAsync, maybe you can use it on your Coroutine but I've never done it that way, tell me if it works ^^

Upvotes: 1

Related Questions