- Home /
How to wait for networkfunction to return a value ?
Hi, i am trying to retrieve the players score from a Google Play Games Scoreboard with
public static void GetPlayerRank(string user, Action<int> rank)
{
if (!isAuthenticated)
{
return;
}
Social.LoadScores(GPGSIds.leaderboard_highscore, scores =>
{
if (scores.Length > 0)
{
Debug.Log("Retrieved " + scores.Length + " scores");
for (int i = 0; i < scores.Length; i++)
{
if (user == scores[i].userID)
{
Debug.Log("Found score with matching ID, the rank is" + scores[i].rank);
rank(scores[i].rank);
break;
}
}
}
else
{
Debug.Log("Failed to retrieve scores");
}
});
}
The Code is in a seperate "PlayGamesController" Script. Now, when my GameOverscreen is set Active i want to Display the players score. My Script for the GameOverscreen looks like this :
public class GameOverMenu : MonoBehaviour {
[SerializeField]
private TextMeshProUGUI playerRankText;
private int rank = 0;
private bool gameOverShown = false;
private string userID;
// Start is called before the first frame update
void Start()
{
userID = PlayGamesController.userID;
Debug.Log("GameoverMenu" + userID);
}
// Update is called once per frame
void Update()
{
if (this.gameObject.activeSelf && !gameOverShown)
{
ShowPlayerRank();
}
}
void ShowPlayerRank()
{
gameOverShown = true;
PlayGamesController.GetPlayerRank(userID, (status) => { rank = status; });
playerRankText.text = "Your rank is " + rank;
Debug.Log("Players rank is " + rank);
}
}
My Problem is, that the functions are not being called in the right order.
My Console prints the following :
"Gameovermenu a_38007121271874574" (from the Startmethod if the GameOverScreen) "Players rank is 0" (from the ShowPlayerRank()) "Retrieved 1 scores" (from the GetPlayerRank() Method) "Found score with matching ID, the rank is 1"(from inside the forloop in the GetPlayerRank())
As you can see, the rank (which is 0) is getting displayed before the actual rank can be retrieved.
How do i wait for the GetPlayerRank() function to retrieve the rank and then call ShowPlayerRank() in the GameoverScript ?
Thanks in advance !
Answer by Bunny83 · Nov 03, 2019 at 11:55 PM
You don't wait for the GetPlayerRank method. That's why you have a callback method which is called when the data has arrived:
playerRankText.text ="Loading rank ...";
PlayGamesController.GetPlayerRank(userID, (status) => {
rank = status;
playerRankText.text = "Your rank is " + rank;
Debug.Log("Players rank is " + rank);
});
Ah okay, that makes sense. Guess i have to read more about callbackmethods. I did this with a tutorial so i don't really know what i am doing ^^