Unity Singleton Monobehaviour component, that can be attached to Game Objects. You can use SingletonPersistent
to persist the instance among scenes
or just Singleton
class to use the same instance on the only one scene.
- Managers that should use the same instance among scripts (e.g GameManager, ScoreManager, InputManager...)
- When you need use any component that depends of a Game object in the scene (e.g access
AudioSource
inside of an singleton)
Consider use a ScriptableObject instead
Create a script that inherits from Singleton<MyScript>
passing the script class by generics:
public class GameManager : Singleton<GameManager> {
...
}
In any other script, access the Instance
property. The value of this property should be equal from any script:
public class PlayerController : Monobehaviour {
private void Awake() {
// Get the singleton instance
var gameManager = GameManager.Instance;
}
}
The implementation here was based in this gist above!!