Unity C#实现缓存池

Unity C#实现缓存池 优化性能

具体实现代码

// An highlighted block
public class Pool : Single<Pool> {
	//缓存池父节点
	private GameObject fatherPoint;
	//记录所有池子的字典
	Dictionary<string, Stack<GameObject>> allPool = new Dictionary<string, Stack<GameObject>>();

	//Resources文件夹下对应资源文件夹绝对路径
	private string localStr;
	//存储资源名字
	private List<string> prefabStr;
	//存储 名字对应资源预制体
	private Dictionary<string, Object> perfabDic;

    protected override void Awake()
    {
		base.Awake();
		fatherPoint = GameObject.Find("Pool");
		localStr = @"D:\zwt\facebookDemo\Assets\Resources";
		prefabStr = new List<string>();
		perfabDic = new Dictionary<string, Object>();
		this.GetResName();
		this.LoadRes();
	}

	//获取资源名
	private void GetResName()
	{
		DirectoryInfo folder = new DirectoryInfo(localStr);

		//
		foreach (FileInfo file in folder.GetFiles("*.prefab"))
		{
			string fileName = this.CancelBackName(file.Name);
			prefabStr.Add(fileName);
		}
	}

	//消除文件名后缀
	private string CancelBackName(string name) {
		string newStr="";
        for (int i = 0; i < name.Length; i++)
        {
			//读到.号就退出 不要它的后缀名
			if (name[i] == '.') {
				break;
			}
			newStr += name[i];
        }
		return newStr;
	}

	//加载所有资源
	private void LoadRes() {
        for (int i = 0; i < prefabStr.Count; i++)
        {
			Object obj= Resources.Load(prefabStr[i]);
			perfabDic.Add(prefabStr[i],obj);
        }
	}

	//放入缓存池
	public void Put(string key,GameObject obj) {
		//判断pool中是否有对应键key
		//有的话就直接放入对应字典
		if (allPool.ContainsKey(key)) {
			allPool[key].Push(obj);
		}
		else
		{
			Stack<GameObject> newPool = new Stack<GameObject>();
			allPool.Add(key, newPool);
			newPool.Push(obj);
		}
		obj.transform.parent = fatherPoint.transform;
		obj.SetActive(false);
	}


	//从缓存池中取出 *prefab是模板 *position是取出位置 *rotation是克隆方向
	public GameObject Get(string key,Vector3 position,Quaternion rotation)
    {
	
		判断池子中有无对应的key 并且对应key的池子中有对象
		if (allPool.ContainsKey(key) && allPool[key].Count>0) {
			GameObject targetObj = allPool[key].Pop();
			targetObj.transform.position = position;
			targetObj.transform.rotation = rotation;
			targetObj.transform.parent = null;
			targetObj.SetActive(true);
			return targetObj;
		}
		else {
			//不满足条件则自己克隆
			GameObject targetObj = GameObject.Instantiate((GameObject)perfabDic[key], position, rotation);
			return targetObj;
		}
		
	}


}

.

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值