We can declare a generic T that will be used to represent everything that inherits from the class
//where T sets limits on T, class indicates that this is a class, new indicates that objects can be created, and new must be placed last
public class NormalSingleton<T> where T : class.new(a){
// Static field
private static T _single;
// Static attributes
public static T Single
{
get
{
// Check whether the field has been assigned a value
if (_single == null)
{
// NEW an object if empty
T t = new T();
// Check to see if this object inherits Monobehaviour. If so, you can use mono singletons to inherit
if (t is MonoBehaviour)
{
Debug.LogError(message: "Mono class please use MonoSingleton");
}
// Give this object to _single
_single = t;
}
/ / return value
return_single; }}}Copy the code
When using a singleton class, fields must be declared as attributes, and singletons can only be used through methods or methods of attributes