2017-11-19 2 views
0

Ich habe diesen Code hier:Einheit und Facebook: null Erste anstelle des tatsächlichen Ergebnis zurückgegeben

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

Doch irgendwie, wenn ich die GetProfilePic Funktion aufrufen, es gibt null zurück, obwohl der „Erfolg“ Nachricht gedruckt in der Konsole. Ich habe die Facebook ID richtig eingerichtet und so kann es nicht sein. Was passiert hier und wie kann ich das beheben?

+0

In welcher Zeile erhalten Sie Null Referenz Ausnahme? – ZayedUpal

+0

Sie haben hier nicht die _asynchronous_ Anfragen richtig behandelt. In JS wäre dies ein Duplikat von https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call - in Unity, es ist wahrscheinlich nicht so viel anders, Also geh und erforsche, wie es dort richtig gehandhabt wird. – CBroe

Antwort

0

So habe ich eine Lösung gefunden. Es stellte sich heraus, dass Async-Anfragen nicht korrekt behandelt wurden, wie CBroe erwähnt hat.

Mein neuer Code verwendet jetzt das Versprechen Design-Muster, ähnlich wie es in JavaScript geschehen ist

ich den Code hier verwendet richtig, sie umzusetzen (nicht UnityScript!): https://github.com/Real-Serious-Games/C-Sharp-Promise

Das jetzt ist mein neuer 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; 
} 

Dann wird diese Funktion auf diese Weise genannt:

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

Hoffe das hilft jemandem aus!

Verwandte Themen