Wanzyee Studio

Agent to implement the singleton pattern for UnityEngine.MonoBehaviour. More...

Properties

static T instance [get]
 Get the singleton instance. More...
 

Detailed Description

Agent to implement the singleton pattern for UnityEngine.MonoBehaviour.

Not required to derive from any specific class, since C# inheritance is so precious. This finds the existed instance and check if multiple, creates one if not found. Set Object.DontDestroyOnLoad() if the instance is created by this. The others found, created manually or by scripts, should be maintained by the creator. It might need to check and destroy duplicated when Awake().

In the general case, singleton should be implemented in the certain class for better enclosing. And sometimes, we do need to manually create one to edit in the Inspector. Make an agent for UnityEngine.MonoBehaviour to make it easier in the common case. This'll remind the user to fix with exceptions when the code or scene setup incorrectly in edit mode only. And pop up a dialog if tries to create in edit mode, to avoid making scene dirty silently.

Since we can't protect the constructor without inheritance. For the purpose of better enclosed programming, here's usage limitations:

  1. Only allow the class of current singleton to access.
  2. Only allow one method to access to keep the code clean.
  3. Don't assign to a delegate, otherwise we can't keep the same accessor.
  4. Don't access from any constructor or assign to a field, that makes out-of-date.

Example to wrap to access, call this in a method or property:

public class SomeComp : MonoBehaviour{
public static SomeComp instance => Singleton<SomeComp>.instance;
}

Example to maintain in Awake() to avoid duplicated, check to keep or destroy:

private void Awake(){
if(this != instance) Destroy(this);
else DontDestroyOnLoad(gameObject);
}
Template Parameters
TThe component type.
Type Constraints
T :MonoBehaviour 

Property Documentation

T instance
staticget

Get the singleton instance.