如何在统一引擎中从 Facebook API 获取用户名和用户个人资料图片?

How to get Username and User Profile Picture from Facebook API in unity engine?

我想在我的 unity 游戏中实现用户登录,但我无法从他们的 Facebook id 获取用户个人资料图片。 显示的是用户名,但未显示个人资料照片。它显示空白。我也没有收到任何错误! 图像的精灵正在改变但不显示在屏幕上。 这是代码:

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);
    }
}

Sprite.Create 需要

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

我怀疑您的硬编码 128 x 128 像素只是一个部分,而不是整个纹理,具体取决于图片的实际图像尺寸。

而且还需要

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

您使用的是 new Vector2(),表示左下角。一般来说,对于个人资料图片,我宁愿假设枢轴应该是纹理的 center 并使用

Vector2.one * 0.5f

new Vector2(0.5f, 0.5f)

所以假设下载本身确实有效,并且正如您所说的那样您没有收到错误,您可能宁愿使用例如

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

或者如果您的目标是使用正方形截面,无论您可以使用何种尺寸

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);