You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESX框架物品合成代码求助:实现数组多物品匹配合成

ESX框架多物品可选合成脚本修复方案

问题分析

原代码的核心问题在于:

  • 错误地将物品数组直接传入合成函数,未做遍历检查
  • check函数逻辑混乱,在循环内定义函数完全不符合语法规范
  • 合成函数无法处理数组类型的物品参数,只能识别单个物品ID

修复思路

  1. 新增工具函数,遍历目标物品数组,检查玩家是否拥有其中任意一个物品,并返回该物品ID
  2. 在物品使用回调中,先调用工具函数确认玩家拥有符合条件的物品,再执行合成流程
  3. 调整合成函数的参数逻辑,确保接收单个物品ID而非数组
  4. 优化提示信息,当玩家缺少物品时,明确列出可选的物品列表

修复后完整代码

ESX = nil
 
local backwoodItems = {'backwoods_grape', 'backwoods_honey', 'backwoods_russian_cream'}

TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)

-- 检查玩家是否拥有数组中的任意一个物品,返回拥有的物品名或nil
function hasAnyOfItems(xPlayer, itemArray)
    for _, itemName in ipairs(itemArray) do
        if xPlayer.getInventoryItem(itemName).count >= 1 then
            return itemName
        end
    end
    return nil
end

ESX.RegisterUsableItem('whitewidow', function(source)
    local xPlayer = ESX.GetPlayerFromId(source)
    -- 检查玩家是否拥有任意一种backwood
    local ownedBackwood = hasAnyOfItems(xPlayer, backwoodItems)
    
    if ownedBackwood then
        combineTwoItems(source, xPlayer, 'whitewidow', ownedBackwood, 1, 'jointwhitewidow', 1, "Blunt of White Widow", 10000, "mp_arresting", "a_uncuff")
    else
        -- 生成提示文本,列出所有可选物品
        local itemList = table.concat(backwoodItems, ", ")
        TriggerClientEvent('esx:showNotification', source, '你需要至少1个以下物品中的一种:~r~'.. itemList ..'~s~ !')
    end
end)

function combineTwoItems(source, xPlayer, useItem, needItem, needItemCount, resultItem, resultItemCount, progressbarTitle, progressbarDuration, animationClass, animation)
    local itemCount = xPlayer.getInventoryItem(tostring(needItem)).count
    if itemCount >= needItemCount then
        TriggerClientEvent('ScriptCombineItems:playanimation', source, progressbarTitle, progressbarDuration, animationClass, animation)
        Citizen.Wait(progressbarDuration)
        xPlayer.removeInventoryItem(useItem, 1)
        xPlayer.removeInventoryItem(needItem, needItemCount)
        xPlayer.addInventoryItem(resultItem, resultItemCount) 
    else
        TriggerClientEvent('esx:showNotification', source, '你需要 '.. needItemCount.. 'x ~r~'.. needItem .. '~s~ !')
    end
end

关键修改点说明

  • hasAnyOfItems工具函数:遍历物品数组,逐个检查玩家背包中的物品数量,找到第一个符合条件的物品后立即返回,避免无效遍历
  • 物品使用回调优化:先确认玩家拥有可选物品之一,再调用合成函数,否则弹出包含所有可选物品的提示
  • 变量命名规范:将原backwood数组重命名为backwoodItems,更清晰表达变量用途
  • 错误提示优化:当玩家缺少物品时,明确列出所有可用于合成的物品选项,提升用户体验

内容的提问来源于stack exchange,提问作者One Deep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 07:57:12