Search code examples
c#facebookauthenticationunity-game-enginefacebook-unity-sdk

How to Logout from Facebook and switch a user?


I logged in to facebook with a user on my app.

Later when I log out manually this user on my Facebook app and on the browser,

(FB.IsLoggedIn) still returns true. For some reason, the old profile is saved and I can't login with a new user

Here is my code:

public void FacebookLogin()
{
    if (FB.IsLoggedIn)
        FB.LogOut();  //it doesn't work, user is still logged in


     var permissions = new List<string>() {"email"};
      FB.LogInWithReadPermissions(permissions);  //trying to login a new user, but the last user is still logged in

Solution

  • Change your FacebookLogin function to a coroutine function. By doing this, you can check if the user is logged in, log the user out then wait every frame until FB.IsLoggedIn is false before you can login another user. Also add a timer to the wait so that when FB.IsLoggedIn is never false within x amount of time, the function won't continue to run but show some error and exit.

    public IEnumerator FacebookLogin()
    {
        //5 seconds loggout time
        float waitTimeOut = 5f;
    
        //Log out if loggedin
        if (FB.IsLoggedIn)
            FB.LogOut();  //it doesn't work, user is still logged in
    
        //Wait until logout is done. Also add a timeout to the wait so that it doesnt wait forever
        float timer = 0;
        while (FB.IsLoggedIn)
        {
            if (timer > waitTimeOut)
            {
                Debug.LogError("Failed to log out within " + waitTimeOut + " seconds");
                yield break;
            }
            timer += Time.deltaTime;
            yield return null;
        }
        Debug.Log("Successfully logged out. Now logging another user in");
        var permissions = new List<string>() { "email" };
        FB.LogInWithReadPermissions(permissions);  //trying
    }
    

    If you still have issue with this, you need to file for a bug report on the facebook-sdk-for-unity Github page with the code in this answer.