Lua实现的对象池,Unity

来源:互联网 发布:淘宝店铺ppt 编辑:程序博客网 时间:2024/06/06 14:29
local PrefabObjectPool = {}
PrefabObjectPool.__index = PrefabObjectPoolfunction PrefabObjectPool.New(prefab,capcity)if prefab == nil thenerror("[PrefabObjectPool]prefab should not be nil")endlocal self = {}setmetatable(self,PrefabObjectPool)self.prefab = prefabself.queue = LuaQueue.New()self.usedItems = LuaList.New()self.capcity = capcityreturn selfend-- 预先生成指定个数的对象-- count 需要生成的个数,最大不能超过池大小,若为空则表示直接将池填充满function PrefabObjectPool:Prewarm(count)if count == nil thenif self.capcity == nil thenerror("[PrefabObjectPool]invalid state")elsecount = self.capcityendelseif count > self.capcity thencount = self.capcityendfor i=1,count dolocal obj =  GameObject.Instantiate(self.prefab)self:Put(obj)endend-- 回收一个对象到对象池function PrefabObjectPool:Put(obj)if self.usedItems:Contains(obj) thenself.usedItems:Remove(obj)obj:SetActive(false)self.queue:Enqueue(obj)elseerror("[PrefabObjectPool]invalid state")endend-- 从对象池中获取一个对象,若池为空的,则从Prefab创建一个新的-- 当对象到达池上限时,会把最早使用的对象回收并作为新对象返回function PrefabObjectPool:Get()local obj = nilif self.queue.Count == 0 thenif self.usedItems.Count == self.capcity thenobj = self.usedItems[0]obj:SetActive(false)self.usedItems:RemoveAt(0)elseobj = GameObject.Instantiate(self.prefab)endelseobj = self.queue:Dequeue()endself.usedItems:Add(obj)obj:SetActive(true)return objend-- 将所有被使用的对象全部回收function PrefabObjectPool:RecycleAll()local count = self.usedItems.Countfor i=count-1,0, -1 dolocal item = self.usedItems[i]self:Put(item)endself.usedItems:Clear()end--清空对象池Destroyfunction PrefabObjectPool:Clear()self:RecycleAll();for i = 0, self.queue.Count - 1 doGameObject.Destroy(self.queue:Dequeue());endself.queue:Clear();endreturn PrefabObjectPool