Beginner_
Beginner_

Reputation: 695

GameObject.SetActive() inside Firebase Authentication not called

I am trying to use Firebase to authenticate users.The following code is called when the user enters the email address and password and logs in.The characters entered by the user are substituted for Email and password respectively.

[SerializeField]
GameObject Obj;
auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
  if (task.IsCanceled) {
    Debug.Log("1");
    Obj.SetActive(true);
    return;
  }
  if (task.IsFaulted) {
    Debug.Log("1");
    Obj.SetActie(true);
    return;
  }

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

The problem here is that the Obj is not displayed when the user fails or canceled to log in. Another thing to note is that Debug.Log ("1") is being called.

If I call the following at other times, Obj will be displayed.

void ShowObj()
{
    Obj.SetActive(true);
}

This means that there is no problem with Obj itself.

help me. Thank you.

Upvotes: 0

Views: 215

Answers (1)

Iggy
Iggy

Reputation: 4888

Most of the Unity Engine API is not thread-safe.

The ContinueWith is running on a different thread, and so you can not set Obj.SetActive(true)

You can do what Patrick Martin from Firebase recommends:

IEnumerator RegisterUser(string email, string password)
{
    var auth = FirebaseAuth.DefaultInstance;
    var registerTask = auth.CreateUserWithEmailAndPasswordAsync(email, password);

    yield return new WaitUntil(() => registerTask.IsCompleted);

    if (registerTask.Exception != null)
    {
        Debug.LogWarning($"Failed to register task with {registerTask.Exception}");
        Obj.SetActive(true);
    }
    else
    {
        Debug.Log($"Successfully registered user {registerTask.Result.Email}");
    }
}

This way you wait in the main thread until the other thread IsCompleted, which allows you to set Obj.SetActive(true).

Upvotes: 2

Related Questions