|
|
楼主
发表于 2026-6-5 00:01:39
|
显示全部楼层
实战:子弹/伤害数字对象池
local ObjectPool = require("ObjectPool")
-- 伤害飘字对象池
local DamageTextPool = ObjectPool.new(
function()
-- 创建一个伤害显示对象
return { visible = false, value = 0, x = 0, y = 0, timer = 0 }
end,
function(obj)
-- 归还时清空状态
obj.visible = false
obj.value = 0
obj.timer = 0
end
)
function ShowDamage(x, y, value)
local txt = DamageTextPool:acquire()
txt.x, txt.y, txt.value, txt.visible = x, y, value, true
SetTimer(1500, function()
DamageTextPool:release(txt) -- 1.5秒后归还
end)
end
-- 高频调用不再频繁分配内存
for i = 1, 100 do
ShowDamage(math.random(0,1000), math.random(0,1000), math.random(1, 9999))
end
print("总创建对象数: " .. DamageTextPool:totalCreated()) -- 远小于100 |
|