NakedPython
NakedPython

Reputation: 930

Unity/C#: Resetting a whole script back to it "Original" State

I'm working a game in Unity and I've got a Script where I save a lot of values in multiple variables, which I then use in other scripts. You could say its my GameState. The Script itself is not a GameObject, it purely exists to save values. When I start my game the "GameState" has some basic values like Name, TeamName, Money and tons of more variables which are static and filled with pre-set values.

Now comes my problem. If the player plays through the game and picks some options, functions get triggered which change the values in the GameState, like for example he'll receive more money, so the value for money in the GameState changes. But the player also has the option to completely "restart" the game by going back to the main menu (where I use a LoadScene Function). Problem is that the values in the GameState remain changed when he goes back, so when he starts a new game, he doesn't got the pre-set values, but the ones from his last game.

So my question would be, is there an easy way to reset my GameState completely to its original values? I know I could save the default values somewhere and then make a check to see if the game is reloaded to then use them, but I've already got like 60-70 variables in there and don't really want to create another 60-70 just for the default values (unless there is no other option). So does anyone have an idea how I could do that?

I don't think showing the code of the GameState does much, since its really just looking like:

public class GameState
{
    //Team
    public int TeamID;
    public string TeamName;
    public string TeamColor;
    etc...
} 

Upvotes: 0

Views: 1936

Answers (1)

leo Quint
leo Quint

Reputation: 787

GameState is a class to contain data. An easy way to create default is to serialize it : add [System.Serializable] on top of the class declaration.

Now you can have say an object in your main scene called default values which has a public/serialized field of type GameState. You can set those in the editor save the scene and bam. Now to reset all the values to default you just copy the default to the current/active set of data.

If you want to expand a bit on that you can also turn the class into a scriptableObject but I don't think you need that.

Upvotes: 3

Related Questions