Hello there! Today I will do another short and sweet post! I like it better this way so it’s easier to follow what’s going on. Last post was about creating a variable class that could be extended into multiple types to store data like integers, float, etc. Next step for me was to create a way to handle variables that could be accessed easily by other scripts, so I created a GlobalVariables class. The main purpose of this class is to store variables that I define as ‘global’, good example would be settings for player controllers such as mouse sensitivity or inverted controls. Maybe you could also use it for keybindings if wanted, but I found that it is easier if you just create your own input handler. Anywho, here’s the code:
The reason why the dictionary stores variables as objects its because it is a generic class, so this was the only way I found that would work! I was debating whether to make global variables a singleton-monobehaviour class, but I have learned that there might be cases where scripts might try to access the a variable before the instance of the singleton is created (I have found this to be the case when using networking, Unet to be more specific).
At the same time I also updated the variable class just so that it registers only when you check the global variables option. It also removes itself from the dictionary whenever its destroyed. This is very important, especially when you want to register variables that might only be used in specific scenes.
And that’s all for today. I feel like although I did a bit of code today I learned more about how to work with generic types in data structures. I’ve found that you don’t have to write a lot of code when using them! Feel free to leave a comment/suggestions/etc. I know I said I would go over events on this post, but I will leave it for the next one.