Unity的游戏设计模式:单例模式

当某个对象,只想存在唯一一个实例的时候,并且可以全局访问。

整一个MonoSingleton的基类出来,然后在想要使用单例的类继承。

using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour 
{
//得是静态的
   private static T instance;
//提供全局访问点Instance
   public static T Instance { 
        get { 
            if (instance == null) {
                instance = FindObjectOfType<T>();
                if (instance == null) {
                    Debug.LogError(message: typeof(T).Name +"在场景中没有引用对象");
                }
            }
            return instance;
        } 
   }

    void Start() {
//如果你想把这个实例带到下一个场景
        if (instance == null)
        {
            DontDestroyOnLoad(gameObject);
        }
        else
//如果读取下一个场景也有这个实例,就把原来的摧毁
        {
            Destroy(gameObject);
        }
    }
}

然后要用的时候

例如:

using UnityEngine;

public class T : MonoSingleton<T>
{
    public float hp = 1f;
}

别的类调用此实例的时候

例如:

T.Instance.hp -= 1f;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值