我这里有这段代码:
private Texture profilePic;
public Texture GetProfilePic()
{
FB.API("me/picture?width=100&height=100", HttpMethod.GET, ProfilePicCallback);
return profilePic;
}
private void ProfilePicCallback(IGraphResult result)
{
if (result.Error != null || !FB.IsLoggedIn)
{
Debug.LogError(result.Error);
}
else
{
Debug.Log("FB: Successfully retrieved profile picture!");
profilePic = result.Texture;
}
}
然而,不知何故,当我调用 GetProfilePic
函数时,即使"成功"消息打印在控制台中,它也返回 null。我已经正确设置了Facebook ID之类的东西,所以不可能是那样的。这里发生了什么,我该如何解决这个问题?
所以我找到了解决这个问题的方法。事实证明,正如 CBroe 所提到的,我没有正确处理异步请求。
我的新代码现在使用 Promise 设计模式,类似于在 JavaScript(不是 UnityScript!(中完成的方式。
我在这里使用代码来正确实现它:https://github.com/Real-Serious-Games/C-Sharp-Promise
这是我的新代码:
public IPromise<Texture> GetProfilePic()
{
var promise = new Promise<Texture>();
FB.API("me/picture?width=100&height=100", HttpMethod.GET, (IGraphResult result) =>
{
if (result.Error != null || !FB.IsLoggedIn)
{
promise.Reject(new System.Exception(result.Error));
}
else
{
promise.Resolve(result.Texture);
}
});
return promise;
}
然后,以这种方式调用此函数:
GetProfilePic()
.Catch(exception =>
{
Debug.LogException(exception);
})
.Done(texture =>
{
Debug.Log("FB: Successfully retrieved profile picture!");
// Notice that with this method, the texture is now pushed to
// where it's needed. Just change this line here depending on
// what you need to do.
UIManager.Instance.UpdateProfilePic(texture);
});
希望这对某人有所帮助!