Game Development Reference
In-Depth Information
//public property for manager
public string MyTestProperty = "Hello World";
void Awake()
{
//Save our current singleton instance
Instance = this;
}
//public method for manager
public void DoSomethingAwesome()
{ }
}
The preceding code is just a very basic singleton implementation, which you can attach
this to any game object in the scene.
Then, you can access the properties and functions within the singleton script by simply
calling the following method from anywhere within your project:
//Set the public property of the singleton
MySingletonManager.Instance.MyTestProperty = "World Hello";
//Run the public method from the singleton
MySingletonManager.Instance.DoSomethingAwesome();
The class can run like any other class with updates, fixed updates, and so on. It can also be
expanded very quickly.
One of the other common uses of this pattern is the use of global variables for your pro-
ject. However, if you intend to use your singleton class across the scenes, you will also
need to ensure that it is not destroyed when the scene unloads with a simple update. This
is done by calling DontDestroyOnLoad when you initialize the class, as shown in the
following code:
public class MySingletonManager : MonoBehaviour {
//static singleton property
public static MySingletonManager Instance { get; private
Search WWH ::




Custom Search