public class SingleScriptClass { public int game = 0; private static SingleScriptClass _instance;
public static SingleScriptClass Instance() { if (null == _instance) _instance = new SingleScriptClass(); return _instance; } }
这样每次调用时候Instance后面必须加一对括号,很难受,那么还有一种办法,就是使用属性了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public class SingleScriptClass { public int game = 0;
private static SingleScriptClass _instance;
public static SingleScriptClass Instance { get { if (null == _instance) { _instance = new SingleScriptClass(); } return _instance; } } }
那么怎么调用?直接跨脚本调用,像下面这样。
1 2 3 4 5 6 7 8 9 10 11 12
using UnityEngine;
public class Test : MonoBehaviour { // Start is called before the first frame update void Start() { int game = SingleScript.Instance.game; //int game2 = SingleScriptClass.Instance().game; int game3 = SingleScriptClass.Instance.game; } }
public class SingleMode<T> where T : class , new() //限制继承自单例类的类型,必须是类,必须new() { private static T instance; public static T Instance { get { if (null == instance) { instance = new T(); }
return instance; } } } public class TestSingle : SingleMode<TestSingle> { public int game = 0; }