网上介绍对象池的文章有很多,但是总感觉代码不太清晰,并不适合新手学习
最近在一个工程里看到一段对象池的代码感觉不错,故分享一下
[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);
}
兄弟连IT教育与全球移动游戏联盟(GMGC)共同设立中国首家基于高端游戏开发的兄弟连&GMGC手游学院!高薪就业,就学手游开发,详情咨询官网客服:http://game.lampbrother.net/
学PHP、Linux、HTML5、UI、Android等视频教程(课件+笔记+视频)!联系Q2430675018
参加活动领取兄弟连原创视频教程光盘合集:http://www.lampbrother.net/newcd.html