你的代码整体结构不错,我来帮你优化一下,提升执行效率:
```lua
-- 将堆转换为栈 提升速度
local GUI = GUI
-- 缓存屏幕尺寸,避免重复调用
local screenWidth, screenHeight
local function getScreenSize()
if not screenWidth then
screenWidth = SL:GetMetaValue("SCREEN_WIDTH")
screenHeight = SL:GetMetaValue("SCREEN_HEIGHT")
end
return screenWidth, screenHeight
end
GUINpc = function(uiname)
local w, h = getScreenSize()
local root = GUI:Win_Create("win_"..uiname, w/2, h/2)
if GUI:Win_IsNull(root) then
SL:print("创建窗口失败")
return nil, nil
end
GUI:LoadExport(root, "NewUI/"..uiname)
local ui = GUI:ui_delegate(root)
if not GUI:Win_IsNull(ui.bg) then
GUI:setTouchEnabled(ui.bg, true)
GUI:Win_SetSwallowRightMouseTouch(ui.bg, true)
end
if not GUI:Win_IsNull(ui.bt1) then
GUI:addOnClickEvent(ui.bt1, function()
GUI:Win_Close(root)
end)
end
return root, ui
end
function GUI:Onclick(widget, func)
if GUI:Win_IsNull(widget) then
SL:print("控件为空,无法设置点击事件")
return
end
GUI:setTouchEnabled(widget, true)
GUI:addOnClickEvent(widget, func)
end
-- 测试代码
-- local testWin, testUI = GUINpc("test_ui")
-- if testWin then
-- SL:print("窗口创建成功")
-- end
return GUI
```
**优化点说明:**
1. **缓存屏幕尺寸**:使用局部变量缓存`SCREEN_WIDTH`和`SCREEN_HEIGHT`,避免每次调用都从服务端获取
2. **空值检查**:使用`GUI:Win_IsNull()`检查控件是否有效,避免空指针错误
3. **窗口命名唯一**:给窗口添加唯一标识符,便于管理
4. **错误处理**:添加基本的错误检查和日志输出
5. **函数封装**:保持`GUI:Onclick`的封装,但增加空值检查
**建议:**
- 如果频繁创建/销毁UI,考虑使用对象池技术
- 复杂的UI可以预加载资源,减少运行时开销
- 使用`SL:print()`进行调试,方便定位问题
这样代码会更健壮,执行效率也更高!有什么不懂的可以问浮生梦老师哦~