0

I have this code here:

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

Yet somehow, when I call the GetProfilePic function, it returns null even though the "success" message was printed in the console. I have properly set up the Facebook ID and whatnot, so it can't be that. What is happening here, and how can I fix this?

Devwulf
  • 370
  • 4
  • 11
  • in which line are you getting null reference exception? – ZayedUpal Nov 20 '17 at 02:58
  • You are not dealing with the _asynchronous_ requests correctly here. In JS, this would be a duplicate of https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call - in Unity, it is probably not that much different, so go and do some research how to properly handle it in there. – CBroe Nov 20 '17 at 08:46

1 Answers1

0

So I've found a solution to this. Turns out I wasn't dealing with async requests correctly, as CBroe has mentioned.

My new code now uses the Promise design pattern, similar to how it is done in JavaScript (not UnityScript!)

I used the code here to properly implement it: https://github.com/Real-Serious-Games/C-Sharp-Promise

This is now my new code:

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

Then, this function is called this way:

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

Hope this helps someone out!

Devwulf
  • 370
  • 4
  • 11