Why is the variable WinnerScore going crazy? It keeps adding up to infinity. Could sb help me? Here is the code:

void OnGUI()
{
GUI.skin = skin;
GUI.Label(new Rect(40, 200, 2, 2), "Collected Coins: " + tokenCount + “/” + TotalTokenCount.ToString(), skin.GetStyle(“Coin”));
GUI.Label(timerRect, currentTime, skin.GetStyle(“Timer”));
if (startTime < 5f)
{
skin.GetStyle(“Timer”).normal.textColor = WarningColor;
}
else
{
skin.GetStyle(“Timer”).normal.textColor = CustomColor;
}

    if (ShowWinBox)
    {
        Rect WinScreenRect = new Rect(Screen.width / 2 - (winScreenWidth / 2), Screen.height / 2 - (winScreenHeight / 2), winScreenWidth, winScreenHeight);
        GUI.Box(WinScreenRect, "Click continue or press space to load the next level");
        float tokens = (float)tokenCount;
        int currentScore = (int)tokens * (int)startTime;

        **WinnerScore = WinnerScore + currentScore;**

        GUI.Label(new Rect(Screen.width / 2 - (winScreenWidth / 2) + 10, (Screen.height / 2) - 80, 100, 25), "you've finished with " + startTime + " seconds left", skin.GetStyle("Box"));
        if (tokens==1)
        {
            GUI.Label(new Rect(Screen.width / 2 - (winScreenWidth / 2) + 10, (Screen.height / 2) - 55, 50, 25), "you've collected " + tokens + " coin", skin.GetStyle("Box"));

        }
        else
        {
            GUI.Label(new Rect(Screen.width / 2 - (winScreenWidth / 2) + 10, (Screen.height / 2) - 55, 50, 25), "you've collected " + tokens + " coins", skin.GetStyle("Box"));

        }
        GUI.Label(new Rect(Screen.width / 2 - (winScreenWidth / 2) + 10, (Screen.height / 2) - 30, 100, 25), "your score is: " + currentScore, skin.GetStyle("Box"));

        if (SceneManager.GetActiveScene().buildIndex == 8)
        {
            GUI.Label(new Rect(Screen.width / 2 - (winScreenWidth / 2) + 10, ((Screen.height / 2) - 5), 100, 15), "your final score is: " + WinnerScore, skin.GetStyle("Box"));
        }

}

The OnGUI() method is called repeatedly like the Update(), so you have to make sure to only execute the code that changes the score once.

At least in the posted code I cannot see anything that sets tokenCount or startTime to zero, so it will add those values to your score on every gui draw.

I can’t really see what is wrong here but maybe

WinnerScore = WinnerScore + currentScore;

is called more times than it should and it goes like:

currentScore = 1
+
WinnerScore = 1
=
WinnerScore = 2

then it goes

currentScore = 1
+
WinnerScore = 2
=
WinnerScore = 3

and so on.

Why don’t you use NGUI instead of the old one? I guess you’ve got this code inside of OnGUI function which can be called multiple times in a second (read here Unity - Scripting API: MonoBehaviour.OnGUI()), so it adds the currentScore on each call - which leads to infinity