Unity对象池的实现

网上介绍对象池的文章有很多,但是总感觉代码不太清晰,并不适合新手学习
最近在一个工程里看到一段对象池的代码感觉不错,故分享一下

[code]phpcode:

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

public class PoolManager : UnitySingleton<PoolManager> {

	public static Dictionary<Type, Stack<IPoolable>> ObjectPoolDic = new Dictionary<Type, Stack<IPoolable>>();
	public static Dictionary<Type, int> ObjectPoolSizeDic = new Dictionary<Type,int>();
	
	void Start () {

	}
	
	public void RegistPoolableType(Type type, int poolSize)
	{
		if (!ObjectPoolDic.ContainsKey(type))
		{
			ObjectPoolDic[type] = new Stack<IPoolable>();
			ObjectPoolSizeDic[type] = poolSize;
		}
	}
	
	public bool HasPoolObject(Type type)
	{
		return ObjectPoolDic.ContainsKey(type) && ObjectPoolDic[type].Count > 0;
	}
	
	public bool IsPoolFull(Type type)
	{
		if (!ObjectPoolDic.ContainsKey(type))
			return true;
		else if (ObjectPoolDic[type].Count >= ObjectPoolSizeDic[type])
			return true;
		return false;
	}
	
	public IPoolable TakePoolObject(Type type)
	{
		if (ObjectPoolDic.ContainsKey(type) && ObjectPoolDic[type].Count > 0)
		{
			return ObjectPoolDic[type].Pop();
		}
		else
		{
			return null;
		}
	}
	
	public bool PutPoolObject(Type type, IPoolable obj)
	{
		if (!ObjectPoolDic.ContainsKey(type) || ObjectPoolDic[type].Count >= ObjectPoolSizeDic[type])
		{
			GameObject.Destroy((obj as MonoBehaviour).gameObject);
			return false;
		}
		else
		{
			(obj as MonoBehaviour).gameObject.SetActive(false);
			//(obj as MonoBehaviour).transform.parent = GameManager.Instance.PoolRoot;
			ObjectPoolDic[type].Push(obj);
			return true;
		}
	}
}
首先继承自一个单例类,就可以用PoolManager.Instance来获取这个类的单例了
定义了两个字典,一个用来对应 存储对应的 对象类型的栈,一个用来记录实例化的最大个数来控制内存
用的时候Pop,用完了Push
可存储在对象池的对象必须实现IPoolable接口

[code]phpcode:

using UnityEngine;
using System.Collections;

public interface IPoolable {

	void Destroy();
}
destroy里可以这样写

[code]phpcode:

	if (!PoolManager.Instance.IsPoolFull(GetType()))
		{
			PoolManager.Instance.PutPoolObject(GetType(), this);
		}
		else
		{
			GameObject.Destroy(this.gameObject);
		}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值