Fixed score resetting on game over

"It turns out the solution is as simple as one word… static…

I read and tried that proposed solution and was still having 0 score for my “Game Over” Scene until

i read the part where you mention adding “static” would make the code easier and safer and it has resolved the score issue.

Both singleton and your solution both work fine now

Thanks for the link. it helped."

public class GameSession : MonoBehaviour {



    static int score = 0;  // !!HERE

    private void Awake()

    {

        SetUpSingleton();

    }

    private void SetUpSingleton()

    {

        int numberGameSessions = FindObjectsOfType<GameSession>().Length;

        if (numberGameSessions > 1)

        {

            Destroy(gameObject);

        }

        else

        {

            DontDestroyOnLoad(gameObject);

        }

    }

   

    public int GetScore()

    {

        return score;

    }



    public void AddToScore(int scoreValue)

    {

        score += scoreValue;

    }



    public void ResetGame()

    {

        Destroy(gameObject);

        score = 0;

    }

}

it turns out the solution to this infuriating issue was changing the score to a static variable and adding a statement to the reset method that redefines the score int back to zero.
I’m not sure why Rick did not encounter this issue but I’d like to see the lesson updated to include this because I thought I was going crazy and everything I knew was wrong but no it was just an issue with unity and this variable.

1 Like

Sometimes all it takes is one word

1 Like

Privacy & Terms