Unity Singleton 单例类

猴子原创,欢迎转载。转载请注明: 转载自Cocos2Der-CSDN,谢谢! 
原文地址: http://blog.csdn.net/cocos2der/article/details/47335197

今天看到群里有朋友问unity单例的最佳实现方式,下面我我经常用的。贴出来供大家参考。

一、添加单例模板类
using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;

    private static object _lock = new object ();

    public static T Instance 
    {
        get {
            if (applicationIsQuitting) {
                return null;
            }

            lock (_lock) {
                if (_instance == null) {
                    _instance = (T)FindObjectOfType (typeof(T));

                    if (FindObjectsOfType (typeof(T)).Length > 1) {
                        return _instance;
                    }

                    if (_instance == null) {
                        GameObject singleton = new GameObject ();
                        _instance = singleton.AddComponent<T> ();
                        singleton.name = "(singleton) " + typeof(T).ToString ();

                        DontDestroyOnLoad (singleton);
                    }
                }

                return _instance;
            }
        }
    }

    private static bool applicationIsQuitting = false;

    public void OnDestroy ()
    {
        applicationIsQuitting = true;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

这是一个单例模板类,使用就很简单了。

二、定义自己的单例类
using UnityEngine;
using System;

public class GameManager : Singleton<GameManager> {
    public float score;
    void Awake () {
        this.Init();
    }

    private void Init() {
        // Init code
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
三、调用使用
GameManager.Instance.score = 99;
  • 1

如果有更好的实现方式,可以推荐下哦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值