The singleton pattern ensures that instances of a class are unique
Generally speaking, all management classes need to be set to singleton mode. Audio management module, UI management module, object pool singleton mode can be written in various ways, there are very common singleton mode, there are very complex singleton mode. Some singletons need to consider the problem of multi-threaded sharing, so they need to be locked to prevent clutter.
The singleton pattern
- Private static reference
- Private constructor
- Exposed Get methods
Common uninherited Mono singleton
The most common and common singleton pattern base class is written using generics for encapsulation. Through static variables and static static methods, to achieve the uniqueness of the class instance in the process of running the program.
public class BaseManager<T> where T : new()
{
private static T instance;
// It is not necessary to have a private constructor. The main purpose is to prevent the use of new from wasting memory
private BaseManager(){}public static T GetInstance()
{
if (instance == null)
instance = new T();
returninstance; }}Copy the code
The singleton schema base class for scripts that inherit MonoBehaviour
One operational caveat with this approach is to ensure that the script is mounted on only one object in the scene. Otherwise, memory is wasted because instance can only return the instance of the last object to load the script.
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T GetInstance()
{
return instance;
}
protected virtual void Awake()
{
instance = this asT; }}Copy the code
Inherit from MonoBehaviour’s Auto singleton base class
This approach solves the problem of ensuring the uniqueness of the script hanging in the scene.
/// <summary>
///Inherited from a variety of automatically created singleton schema base classes, we do not need to manually support or API to add, if you need to use direct GetInstance on the line
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T GetInstance()
{
// There is no need to manually drag and drop scripts and no need to check the uniqueness of scripts in the scene
if (instance == null)
{
GameObject obj = new GameObject();
// Set the object's name to the name of the script
obj.name = typeof(T).ToString();
// Ensure that the gameObject with this script hanging is not removed when switching scenes.
// The singleton pattern needs to ensure that a single instance of the program is running throughout its entire lifecycle
instance = obj.AddComponent<T>();
}
returninstance; }}Copy the code