Bag = {}
function Bag.Init(isWin32)
-- 网格配置
Bag._ScrollHeight = isWin32 and 214 or 320 -- 容器滚动区域的高度
Bag._PWidth = isWin32 and 338 or 500 -- 容器可见区域 宽
Bag._PHeight = isWin32 and 214 or 320 -- 容器可见区域 高
Bag._IW
你代码中获取背包物品的逻辑有问题。从打印结果来看,物品ID 12256是存在的,但`SL:GetMetaValue("BAG_ITEM_BY_ID", itemId)`返回的是nil,这说明该物品可能不在背包中,或者获取方式不正确。
根据浮生梦老师前端课程内容,背包物品的正确获取方式应该是:
```lua
function Bag.GetItemData()
Bag._itemList = {}
-- 首先获取背包总格子数
local maxBag = SL:GetMetaValue("MAX_BAG") or 0
for _, itemId in ipairs(Bag._targetItemIds) do
-- 遍历背包所有格子查找物品
for pos = 1, maxBag do
local itemInfo = SL:GetMetaValue("BAG_ITEM", pos)
if itemInfo then
local slices = string.split(itemInfo, "#")
if slices and #slices >= 3 then
local itemIdInBag = tonumber(slices[1])
local count = tonumber(slices[3])
if itemIdInBag == itemId and count > 0 then
local itemName = SL:GetMetaValue("ITEM_NAME", itemId)
table.insert(Bag._itemList, {
id = itemId,
pos = pos,
name = itemName or "未知物品",
count = count,
icon = SL:GetMetaValue("ITEM_ICON", itemId)
})
SL:Print("在背包位置" .. pos .. "找到物品:" .. itemName .. ",数量:" .. count)
break -- 找到后跳出内层循环
end
end
end
end
end
SL:Print("获取到指定物品数量:" .. #Bag._itemList)
-- 更新显示
if Bag.UpdateItemDisplay then
Bag.UpdateItemDisplay()
end
end
```
主要问题:
1. `BAG_ITEM_BY_ID`可能不是正确的接口,应该使用`BAG_ITEM`按位置遍历
2. 背包物品信息格式通常是"物品ID#位置#数量",但需要验证实际格式
3. 物品可能在不同背包位置,需要遍历查找
建议先打印一下背包内容确认格式:
```lua
local maxBag = SL:GetMetaValue("MAX_BAG") or 0
for pos = 1, maxBag do
local itemInfo = SL:GetMetaValue("BAG_ITEM", pos)
if itemInfo then
SL:Print("背包位置" .. pos .. ":" .. itemInfo)
end
end
```
这样就能知道背包物品的确切格式,然后调整解析逻辑。