If you have a big list of variables that will never change — say for example, a price list that needs to be referenced — what is the better way to put this into the game? I have three different approaches in my head…
-
Create a simple script of all the vars and attach it to a GameObject
-
Create a simple script of all static vars, negating the need to attach or reference any GameObject
-
Make a static class, which would include all the vars and wouldn’t require me putting ‘static’ in front of each variable (High possibility my assumption is incorrect here?)
I make a GameConstants
class that holds true constants.
public class GameConstants {
public const string PLAYER_TAG = "Player";
public const float PRICE = 1.99;
// ...etc
}
And then I reference it other scripts like:
public class Example {
void Start() {
GameObject.FindObjectsWithTag(GameConstants.PLAYER_TAG);
}
}
I like this approach simply because my constants are in one, central location. You can further organize by splitting them into appropriately name Structs give better documentation such as…
public struct GameTags {
public const PLAYER_TAG = "Player";
public const MINI_MAP_CAMERA_TAGE = "MiniMap";
}
// referenced then like:
public class Something {
void Start() {
GameObject.FindObjectsWithTag(GameTags.PLAYER_TAG);
}
}
It also has the benefit of not having to store a reference to the object holding the values if you just store it on a GameObject.
I’ve had experience with two approached that seem to be robust.
Personally, I like using static classes for these sort of tasks, with public variables or public getters / setters:
public static GameSettings
{
float m_timeScale;
int m_someOtherVariable;
etc...
}
Another approach which I’ve seen being taken, is to create behaviour scripts and do a lookup on awake to resolve references. Personally, I like the first approach better, however this allows you to quickly swap in and out different data sets.
public GameSettings : MonoBehaviour
{
public float m_price = 100.0f;
}
public SomeClassWhichUsesSettings : MonoBehaviour
{
protected GameSettings m_gameSettings;
void Awake()
{
m_gameSettings = FindObjectOfType( typeof( GameSettings ) ) as GameSettings;
}
}
I wasn’t sure if my 3rd choice in my initial post would work but I just tested it and it works perfectly, so I think this is the most simple approach.
static class PriceList
{
var costumePrice = 100;
}
Then access vis script using PriceList.costumePrice
Easy!