推薦閱讀:
換新工作已經一個多月了,每天工作都是那麼的充實,也學習到了許多東西,下面總結一下關於代碼的優化:
字符串的拼接使用string.format()
(1)避免拼接過程中產生新的字符串佔用內存空間
(2)在多語言版本中方便控制語言
在使用for循環的時候,避免重複加載同一資源,避免重複進行相同的運算
例如:
優化前:
for i = 1, table.getn(myTable) do
local myBItem = utils.addchild(group, Asset:LoadAsset(asseturi.getassetpath("timelimitactive", "feedPet/Active53MyBItem")))
end
優化後:
local len = table.getn(myTable)
local res = Asset:LoadAsset(asseturi.getassetpath("timelimitactive", "feedPet/Active53MyBItem"))
for i = 1, len do
local myBItem = utils.addchild(group, res)
end
計時器
在同一界面中,如果有多個東西需要計時,可使用一個計時器,在計時器裏進行for循環即可.方法如下:
在需要計時的地方爲時間賦值,檢測當前計時器是否開啓,未開啓則調用計時器,當某個計時結束時,將其賦空
代碼實現:
--計時器
local function setTime()
this.coroutine = coroutine.start(function()
while true do
if this.gameObject == nil then
return
end
--this.lessTime存放對應文本的計時器
for k, v in pairs(this.lessTime or {}) do
if v < 1 then
--某倒計時結束
this.mainTmType[k] = nil
else
this.lessTime[k] = this.lessTime[k] - 1
tm.text=this.lessTime[k]--顯示
end
end
coroutine.wait(1)
end
end)
end
--倒計時賦值
this.lessTime={}
for i = 1, 4 do
this.lessTime[i]=30
end
--調用
if this.coroutine == nil then
setTime()
end