My project has a lot of objects communicating with a few different global controllers and I’ve been using this technique to access them:
In the controller:
class Controller : MonoDevelop {
public static Controller _;
void Awake() {
_ = this;
}
}
It seems to work well, and I like the fact that I don’t have to have tons of GameObject.Find calls in all of my other scripts. My question is, is this a bad idea? I’ve never actually seen any code where this is done.
Static variables are global in the app. This meaning that after you change the scene its object will be not cleaned up because will be still referenced.
Add this to help unity clean your objects.
void OnDestroy() {
_ = null.
}
The use o FindObjectOfType and cache its value is the unity way of doing this. But no problem.
Static variables may be problematic for automatic serialization (saving & loading). But if you do it yourself or it’s a non issue, then I don’t see any other problems. It may lead to tighter coupling and more difficult code reusability.
When having more of these global objects, what I do is make only one static, let’s call it Game. Then have the other systems as its (non-static) properties. Then you can access them as Game.Player, Game.Controller, Game.AudioManager etc. This avoids the Controller._.var access and also enables you to have more instances, were that ever necessary.
Example:
public class Game : MonoBehaviour {
// Singleton instance of this class
public static Game Instance;
// Non static property
internal Controller controller;
public static Controller Controller {
get {
return Instance.controller;
}
}
void Awake() {
Instance = this;
}
}
It’s called a Singleton pattern (Singleton Pattern | Object Oriented Design), relatively popular thing in OO design. Generally speaking it’s ok to use it, because it simplifies access to these objects a lot, although sometimes it can lead to too many hidden relation between parts of the code in the long run. Imagine that your project grew a lot and you use bunch of Singletons around and suddenly realize that one of these objects can not be singleton, but a few objects (with different values) instead. If the project is big, then it might be difficult to refactor, because your code and data everywhere assumes that there is just one object of type X.