You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Matheus Lessa Rodrigues edited this page Oct 28, 2017
·
1 revision
Singleton
The Singleton design pattern. Ever wanted to access a MonoBehaviour from anywhere in the code? With this pattern, you will be able to MyScript.Instance.someField.
Note
Beware, though, as it's generally accepted that using lots of Singletons is a code smell. What it does is that it introduces a hard dependency between scripts and makes it hard to refactor later. As a reasonable rule of thumb, only use it as a last resort or when prototyping.
Example
usingUnityEngine;usingBitStrap;publicsealedclassMyScript:Singleton<MyScript>{publicintsomeField;}// From another scriptpublicsealedclassSomeRegularScript:MonoBehaviour{privatevoidStart(){Debug.Log("Some global value {0}",MyScript.Instance.someField);}}