Vector3是结构体,在C#中本不会产生GC。但是由于Vector3属于C#的结构体,当Lua使用Vector3时就会产生GC。
通常在使用摇杆时,就会生成许多的Vector3对象,用于设置移动的位置与方向。
我们可以通过在lua中自定义Vector3以为缓存生成出来的Vector3(因为方向值基本上就那么多个,缓存以避免重复生成),来达到减少GC的目的
local Vector3 = {}
setmetatable(Vector3, __UnityEngine.Vector3)
-- 创建Vector3lua或设置res的 x, y, z 值, 结果res 没有就创建
function __Vector3Lua(x, y, z, res)
if res == nil then res = {x = x or 0, y = y or 0, z = z or 0} setmetatable(res, Vector3)
else res.x = x or 0 res.y = y or 0 res.z = z or 0 end
return res
end