Unity3D的单例框架以及单例框架的使用

单例是一种思想

using UnityEngine;
using System.Collections;
using System.Collections.Generic;//写单例框架需要引入


//单例一般都是控制器Manager,单例之间可以互相的调用。

//泛型里面需要定义限制一下(where t 被实例)
public class SingleScript<T>where T:new() {
    /// <summary>
    /// 声明单例,并赋值默认值;
    /// </summary>
    private static T instance = default(T);
    public static T GetInstance(){

        if (instance == null) {
            instance = new T ();
        }
        return instance;
    }
}
public class SimpleSingleTon{
    private static SimpleSingleTon instance;//静态实例
    public static SimpleSingleTon GetInstance(){//返回这样的实例
    //惰性实例化,如果不调用Getinstance,就是不实例化的,不给你分配内存。
        //当你调用的时候再去实例化,这样比较优化的节省内存。
        if (instance == null) {
            instance = new SimpleSingleTon ();
        }
        return instance;
    }
    //为了防止其他类去调用这个类生成这个实例
    //所以把这个构造函数私有
    private SimpleSingleTon(){

    }
}

以上是写的单例框架,接下来是如何调用

public class AudioManager:SingleScript<AudioManager>{
    public float currentAud;
}
public class Demo{
    public Demo(){

        AudioManager.GetInstance ().currentAud = 5;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值