I have a “puppetmaster” script with a few “puppet” scripts doing individual pieces of work e.g. collecting game data, setting up the scene with that data, etc…
These Scripts are only instantiated once within the scene and some are utility functions which are likely to be used through the scene.
I’m wondering if I should make these Static, as it would make these global without having to write the following in each individual Script:
private GameScript gameScript;
private GameScript2 gameScript2;
private GameScript3 gameScript3;
gameScript = gameObject.GetComponent<GameScript>();
gameScript2 = gameObject.GetComponent<GameScript2>();
gameScript3 = gameObject.GetComponent<GameScript3>();
Any ideas? Thanks!
If there must be only one instance of a class then is cannot be static, as static classes can not be instantiated. Instead create a singleton.
However, the vibe I’m getting from your question is that you are in need of a utility class and are asking if it’s a good idea. This is a matter of discussion, and better suited for the forums. However, this is what the good people at StackOverflow have to say about the topic.
I think small general utility classes are a good idea, emphasis on small. I usually make utility classes to shorten often used, long, complicated lines of code, like Instantiating a gameobject x distance away from another. I also try to create utility functions using code that rarely changes, like Unity’s code, because it makes it harder to break things.
If you want the class to run Update or to start coroutines, it needs to be a regular (non-static) Monobehavior, placed on (probably) an empty.
If it only holds data (lives left, score …) and maybe some functions to play with that, then it could be static. But, you often want to use the Inspector to set values, drag in textures and sounds… . So still better to have it be a regular class on an empty.