简易的单例模式与对象池

这是我第一次写博客,博主经验尚浅,还请老铁不吝赐教。

【1.万能单例模式】

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//单例的报错
public class SingletonException : System.Exception{
    public SingletonException(string msg) : base(msg){}
}

//万能单例模式
public abstract class Singleton<T> where T : class,new()
{
    private static T instance = null;
    public static T Instance{
        get{
            if(instance == null)
                instance = new T();
            return instance;
        }
    }

    protected Singleton(){
        if(instance!=null)
            throw new SingletonException("This "+typeof(T).ToString()+" Singleton is not null!");
        Init();
    }

    protected abstract void Init();
}


【2.简易的对象池】

using UnityEngine;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class PoolManager : Singleton<PoolManager>{
    private static GameObject Parent;
    public Dictionary<string, List<GameObject>> Pool;

    protected override void Init(){
        Pool = new Dictionary<string, List<GameObject>>();
        Parent = new GameObject();
        Parent.name = "Pool";
        Parent.SetActive(false);
        GameObject.DontDestroyOnLoad(Parent);
    }

    public void Push(GameObject obj){
        if(obj.transform.parent == Parent.transform)
            return;
        if(!Pool.ContainsKey(obj.name))
            Pool.Add(obj.name, new List<GameObject>());
        obj.transform.SetParent(Parent.transform);
        Pool[obj.name].Add(obj);
        obj.SetActive(false);
    }

    public GameObject Pop(string name, string path = null){
        if(string.IsNullOrEmpty(path)&&!path.Contains("/"))
            path += "/";
        GameObject result = null;
        if(!Pool.ContainsKey(name) || Pool[name].Count == 0){
            if(path==null){
                Debug.LogError("Obj Pool doesn't hava:" + name);
                return null;
            }
            result = Resources.Load(path + name) as GameObject;
            if(result==null)
                Debug.LogError("Cannot find  resource : " + path + name);
            result.name = name;
        }else
        {
            var resultList = from obj in Pool[name] where !obj.activeSelf select obj;
            result = resultList.First();
            if(result.transform.parent!= Parent.transform){
                Debug.LogError("obj not in Pool : " + result.name);
            }
        }
        return result;
    }
}


闲暇时间写的,没有来的及用在项目上,, 如果有错误请评论或者私信我,我会及时更改,谢谢大家的 支持!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值