Search Unity

are globals a good idea to save game states ?..

Discussion in 'Scripting' started by U7Games, Aug 20, 2018.

  1. U7Games

    U7Games

    Joined:
    May 21, 2011
    Posts:
    943
    Hello Friends...

    I´m working on a game that has a lot changes (a RPG game to be direct), so as you can see, there are a lot of game states...

    What is the best practice to save a game state (I´m not meaning to save game, just to write game states).

    For instance:
    I´m in a world map, I have 4 sub levels, once I have completed a sub level, I need to write in somewhere a global var that sub level was successfully completed and then return to world map, once world map is loaded again, it need to read the var to set sub level closed...

    To achieve this, I create a GameObject containing a script that has the global vars (statics), so, I write there "public static bool Sublevel1Completed = true;" then on WorldMap, I create another script and on Awake() function, I read that global var and determine what to do depending the value of that variable.... but I´m not sure if this is a good way...

    Any clues?
    Thanks..
     
    Last edited: Aug 20, 2018
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,779
    If you decide to use static class, you don't need Game Object to store it. You can call it from other scripts anyway.
    There is nothing wrong of having static classes, or fields, as long you know how to handle them nicely, without falling into mess.

    But I advise, you create a reference to the class holding states. It can be useful, if ever need make multiple copies of states.
    Or alternatively, having collection (static, or referenced), like list, or dictionary, to store sets of game states. But digressing.

    Fields is preferably to keep private, as you can have methods, which trigger relevant trigger state. Then you can add conditions inside such method. This way, you can prevent overriding relevant states, when should not be. For example, C state may be only set when A and B states are true. etc. When you make public fields, you can accidentally set state C where A or/and B is false.
     
    U7Games likes this.
  3. U7Games

    U7Games

    Joined:
    May 21, 2011
    Posts:
    943
    That's right, what I need is to set a global shared field that can be read elsewhere ...
    Thanks for the help.