PrefabObjectPool.__index = PrefabObjectPool
function PrefabObjectPool.New(prefab,capcity)
if prefab == nil then
error("[PrefabObjectPool]prefab should not be nil")
end
local self = {}
setmetatable(self,PrefabObjectPool)
self.prefab = prefab
self.queue = LuaQueue.New()
self.usedItems = LuaList.New()
self.capcity = capcity
return self
end
-- 预先生成指定个数的对象
-- count 需要生成的个数,最大不能超过池大小,若为空则表示直接将池填充满
function PrefabObjectPool:Prewarm(count)
if count == nil then
if self.capcity == nil then
error("[PrefabObjectPool]invalid state")
else
count = self.capcity
end
elseif count > self.capcity then
count = self.capcity
end
for i=1,count do
local obj = GameObject.Instantiate(self.prefab)
self:Put(obj)
end
end
-- 回收一个对象到对象池
function PrefabObjectPool:Put(obj)
if self.usedItems:Contains(obj) then
self.usedItems:Remove(obj)
obj:SetActive(false)
self.queue:Enqueue(obj)
else
error("[PrefabObjectPool]invalid state")
end
end
-- 从对象池中获取一个对象,若池为空的,则从Prefab创建一个新的
-- 当对象到达池上限时,会把最早使用的对象回收并作为新对象返回
function PrefabObjectPool:Get()
local obj = nil
if self.queue.Count == 0 then
if self.usedItems.Count == self.capcity then
obj = self.usedItems[0]
obj:SetActive(false)
self.usedItems:RemoveAt(0)
else
obj = GameObject.Instantiate(self.prefab)
end
else
obj = self.queue:Dequeue()
end
self.usedItems:Add(obj)
obj:SetActive(true)
return obj
end
-- 将所有被使用的对象全部回收
function PrefabObjectPool:RecycleAll()
local count = self.usedItems.Count
for i=count-1,0, -1 do
local item = self.usedItems[i]
self:Put(item)
end
self.usedItems:Clear()
end
--清空对象池Destroy
function PrefabObjectPool:Clear()
self:RecycleAll();
for i = 0, self.queue.Count - 1 do
GameObject.Destroy(self.queue:Dequeue());
end
self.queue:Clear();
end
return PrefabObjectPool