A way to keep track of lives on scene load

Hi guys, is there a way to keep track of how many lives left have the player?

I have a gameobject, it have a script attached to it, the player interacts with the gameobject. Inside the script I have a method called Check(). Using a event trigger (pointer click) I call that method to check if the player lose a life or wins a point. The gameobject is set up using the Start() method on the script attached to it.

If the player lose a life then I should do something like

lives --;

So if the initial value was 3, now he will have 2 lives left. Then I need to reload the same scene, and here is where my problem begins…

If I set the amount of lives on the Start() method, when the scene reloads the player will have 3 lives again and of course, that should not happen because the player just lost one life before the scene reload.

I could create an empty gameobject and attach a script to it (let’s call it TempScript) with a variable called livesLeft to store there the amount of lives left, and then use the Awake() method and the known

DontDestroyOnLoad(This);

When the scene reloads the variable livesLeft will not change, so if the player had two lives at reload, after the reload he still will have two lives. The problem using this solution is, how do I set up the initial amount of lives then???

Load scene 1st time → livesLeft = 3 → load gameobject → player interact with gameobject → Check() is called → player lose life → livesLeft = livesLeft - 1 → reload scene → livesLeft = 2 → …

I’m sorry, maybe this is a very simple question, but I can’t see a solution…

Yes, I know about singletons, but I really don’t want to use them unless there is no other choice.

Hi,
In his book, “Mastering Unity Scripting”, Alan Thorn has a nice section on Understanding Singleton objects and statics. To address your particular question – a way to keep track of how many lives a player has remaining, he recommends a “GameManager” class. This type of class is intended to exist as a lone entity and that is the recommended design pattern to use here for your particular question.

Near the end of your post you mention that you really don’t want to use a singleton “unless there is no other choice.” But a Singleton is simply a guaranteed sole instance of an in-memory class during the life of the game. It is statically accessible from anywhere in your game code and is scene independent. As such it is a very light weight and efficient solution for things like player lives, player health, etc. I can’t think of a good reason why you would not want to use a Singleton.

I highly recommend Alan’s book to get comfortable with the different devices that are available such as Singletons. I know for me reading the book has definitely increased my knowledge of Unity coding solutions and general design pattern options.