Home > front end >  How to get Username and User Profile Picture from Facebook API in unity engine?
How to get Username and User Profile Picture from Facebook API in unity engine?

Time:09-17

I want to implement a user login in my unity game but I am unable to get the user profile picture from their Facebook id. The username is showing but not the profile picture. It is showing blank. I am also not getting any errors! The sprite of the image is changing but not displaying on the screen. Here is the code:

void DealWithFbMenus(bool isLoggedIn)
{
    if (isLoggedIn)
    {
        FB.API("/me?fields=first_name", HttpMethod.GET, DisplayUsername);
        FB.API("/me/picture?type=med", HttpMethod.GET, DisplayProfilePic);
    }
}

void DisplayUsername(IResult result)
{
    if (result.Error == null)
    {
        string name = ""   result.ResultDictionary["first_name"];
        FB_userName.text = name;
        Debug.Log(""   name);
    }
    else
    {
        Debug.Log(result.Error);
    }
}

void DisplayProfilePic(IGraphResult result)
{
    if (result.Error == null)
    {
        Debug.Log("Profile Pic");
        FB_userDp.sprite = Sprite.Create(result.Texture, new Rect(0, 0, 128, 128), new Vector2());
    }
    else
    {
        Debug.Log(result.Error);
    }
}

CodePudding user response:

Sprite.Create takes

rect Rectangular section of the texture to use for the sprite.

I suspect that your hard coded 128 x 128 pixels is just a section and not the entire texture depending on the actual image dimensions of the picture.

And it also takes

pivot Sprite's pivot point relative to its graphic rectangle.

You are using new Vector2() which means the bottom left corner. In general for profile pictures I would rather assume that the pivot should be the center of the texture and use

Vector2.one * 0.5f

or

new Vector2(0.5f, 0.5f)

So asuming the download itself actually works and as you say you don't get errors you would probbaly rather use e.g.

FB_userDp.sprite = Sprite.Create(result.Texture, new Rect(0, 0, result.Texture.width, result.Texture.height), Vector2.one * 0.5f);

or if your goal is to use a square section no matter the dimenions you could use

var size = Mathf.Min(result.Texture.width, result.Texture.height);
FB_userDp.sprite = Sprite.Create(result.Texture, new Rect(0, 0, size, size), Vector2.one * 0.5f);
  • Related