I have a high-level limitation when working with C# in Unity. I’m not clear on the best approach. A lot of times I create manager or controller-type classes and it becomes tedious to call their functions from other classes. Here’s an example:
Class: Meta ← runs the whole application at the highest level. Hold variables for universal settings like MusicOn, SoundOn, etc. In charge of loading various scenes.
Class: Game ← runs the gameplay portion of the application. Holds game-related settings like player speed, gravity, jumpHeight, etc. In charge of creating most of the gameplay objects and their controllers.
Class: GUI ← handles menus and HUD. It needs access to settings and functions from high-level classes like Meta and Game, but also low-level instances like Enemy, Player, or Platform.
Questions:
- First of all, right now Meta and Game are scripts attached to an empty gameObject I set up in the Scene. This is kludgy. Ideally I want these classes to exists independent of any objects (Abstract Class?). Meta should always exist anywhere in the application. There I think I can use a static class, but Game doesn’t always exist – it is created by Meta – but I still want to be able to access Main’s functions from any object with a simple one-liner like this:
Main.DoSomething();
Right now I’m doing this by adding a GetComponnent call in the Start event of every single class. This becomes too much when I have more and more controllers that need to be referenced in this way. How can I do the above?
- On the Wiki there’s an AManager C# class available but I don’t understand why functions are called like this:
AManager.instance.Foo();
Instead of like this:
AManager.Foo();
Must “Instance” be used? Is there a way to just call AManager.Foo() directly?
-
I’m not entirely clear on how static classes work. When I set a class to static, does is instantiate itself at the start of the application? Regardless of Scene? What if I want to have different static classes depending on the Scene loaded?
-
Can a static class still have private functions and properties? I want to make use of Getters and Setters.
-
How does a static class work behind the scenes? Is it literally creating an empty game object and attaching itself to that?
-
What is the best way to organize multiple manager classes? Should they all be static? The problem there is, sometimes I don’t need all the manager classes to exist, so I set up a class like Meta or Game to create them. But if I do that, tracking the gameObjects each class is attached to becomes hairy. Would it be better to attach all manager scripts to a single gameObject with AddComponent? And then destroy them with RemoveComponent?
I feel I understand Unity pretty well now, but not knowing how to approach these high-level OO issues is holding me back. Please advise.