-- 展开天命界面
local ID = SL:GetMetaValue("MAIN_ACTOR_ID")
local Lv = SL:GetMetaValue("ACTOR_LEVEL", ID)
local rLv = SL:GetMetaValue("RELEVEL")
GUI:addOnClickEvent(PlayerEquip._ui.destiny_btn, function()
-- 切换天命界面的显示状态
loca
这段代码存在几个问题需要修正:
1. **变量作用域问题**:`pic` 变量在循环外部使用,但在循环内部被引用和赋值,这可能导致变量作用域混乱
2. **资源加载逻辑问题**:`SL:Require` 的调用方式不正确,应该先加载脚本,再调用函数
3. **图片移除逻辑**:`pic` 可能为 nil 时直接调用 `GUI:removeFromParent` 会出错
4. **按钮事件重复绑定**:每次循环都会重新绑定事件,可能导致内存泄漏
修正后的代码:
```lua
-- 展开天命界面
local ID = SL:GetMetaValue("MAIN_ACTOR_ID")
local Lv = SL:GetMetaValue("ACTOR_LEVEL", ID)
local rLv = SL:GetMetaValue("RELEVEL")
-- 用于存储当前显示的图片
local currentDestinyPic = nil
GUI:addOnClickEvent(PlayerEquip._ui.destiny_btn, function()
-- 切换天命界面的显示状态
local destiny_bg = PlayerEquip._ui.destiny_bg
local isVisible = GUI:getVisible(destiny_bg)
if GUI:Win_IsNull(destiny_bg) then
return
end
-- 切换可见性
GUI:setVisible(destiny_bg, not isVisible)
-- 淡入淡出效果
if not isVisible then
GUI:setOpacity(destiny_bg, 0)
GUI:runAction(destiny_bg, GUI:ActionFadeTo(0.2, 255))
end
end)
for k, v in ipairs(PlayerEquip.destiny_config) do
local btn = GUI:getChildByName(PlayerEquip._ui.destiny_list, "btn_"..k)
if Lv < v.level or rLv < v.rlv then
GUI:Button_setBright(btn, false)
else
GUI:Button_setBright(btn, true)
-- 移除之前的事件,避免重复绑定
GUI:removeAllEvent(btn)
GUI:addOnClickEvent(btn, function()
-- 移除之前的图片
if currentDestinyPic and not GUI:Win_IsNull(currentDestinyPic) then
GUI:removeFromParent(currentDestinyPic)
currentDestinyPic = nil
end
-- 创建新图片
local Img = "destiny_img_"..k
currentDestinyPic = GUI:Image_Create(btn, Img, -100, 200, "res/public_win32/bg_npc_01.png")
-- 正确加载并调用脚本
local success, result = SL:Require("qianduan/button/destiny.lua", true)
if success then
-- 假设 destinyHandler 是加载脚本中的函数
destinyHandler(currentDestinyPic, k)
else
SL:Print("加载天命脚本失败:", result)
end
end)
end
end
```
**主要修改点:**
1. 将 `pic` 改为模块级变量 `currentDestinyPic`,确保作用域正确
2. 修正 `SL:Require` 的调用方式,先检查加载结果再调用函数
3. 添加了 `GUI:removeAllEvent(btn)` 避免事件重复绑定
4. 在移除图片前检查图片是否有效
5. 添加了错误处理,当脚本加载失败时打印错误信息
**注意:** 确保 `destinyHandler` 函数在 `qianduan/button/destiny.lua` 脚本中正确定义,并且该脚本返回一个包含该函数的模块。