//调用示例 : 我把 PlayerUI.cs 挂到场景中的物体上执行, PlayerDate.cs 和 UnitySingleton.cs则不需要挂到物体上, 说明:继承UnitySingleton的类 ,如果不挂到物体,就调用的话,就会自动在场景创建一个New Game Object,把继承UnitySingleton的类挂到这个物体上面来执行
PlayerUI.cs using UnityEngine; using System.Collections; public class PlayerUI : MonoBehaviour { void Start () { float hp = PlayerDate.Instance.hp; print(hp); //输出: 9981.142 } }
PlayerDate .cs using UnityEngine; using System.Collections; public class PlayerDate : UnitySingleton <PlayerDate > { public float hp = 9981.141592600f; }
UnitySingleton.cs 单例脚本 using UnityEngine; using System.Collections; public class UnitySingleton <T> : MonoBehaviour where T : Component { private static T _instance; public static T Instance { get { if (_instance == null) { _instance = FindObjectOfType( typeof(T)) as T; if (_instance == null) { GameObject obj = new GameObject (); _instance = (T)obj.AddComponent( typeof(T)); } } return _instance; } } public virtual void Awake() { DontDestroyOnLoad( this.gameObject); if (_instance == null) { _instance = this as T; } else { Destroy(gameObject); } } }
//========================下面是第二种单例情况,类不是继承MonoBehaviour的单例,也就是不在是Component组件类,只需new 类;就能执行的类 /// <summary> /// 这个类用于不是继承MonoBehaviour类的单例类, /// abstract关键是防止这个类被独自使用,这个类只能被继承使用, /// lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁。这样防止多线程下同时执行该代码 /// </summary> /// <typeparam name="T"></typeparam> public abstract class Singleton <T> where T : new() { private static T _instance; static object _lock = new object(); public static T Instance { get { if (_instance == null) { lock (_lock) { if (_instance == null) _instance = new T(); } } return _instance; } } }
|