查看: 764|回复: 0
打印 上一主题 下一主题

[其他] UnitySingleton 单例脚本

[复制链接]
may    

8830

主题

81

听众

7万

积分

首席设计师

Rank: 8Rank: 8

纳金币
52352
精华
343

最佳新人 热心会员 灌水之王 活跃会员 突出贡献 荣誉管理 论坛元老

跳转到指定楼层
楼主
发表于 2016-7-31 18:34:58 |只看该作者 |倒序浏览

//调用示例 :
我把 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;
        }
    }
}

分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

手机版|纳金网 ( 闽ICP备2021016425号-2/3

GMT+8, 2025-8-18 23:53 , Processed in 0.068161 second(s), 28 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部