Foundry VTT宏开发问题:无法识别Actor背包中的治疗药水
问题分析与解决方案
核心问题
你的代码无法找到目标物品的原因是错误使用了item.value属性匹配物品名称。在Foundry VTT中,物品的名称字段是item.name,而非item.value——value通常用于存储物品的数量、数值类属性,并非名称字段。
修正后的关键代码
将查找药水的代码行替换为:
let healthpotion = actor.items.find(item => item.name === "Potion of Greater Healing")
额外验证建议
如果替换后仍有问题,可以在控制台打印所有物品的属性,确认匹配字段的准确性:
actor.items.forEach(item => console.log(item.name, item.id, item.system));
这能帮你确认物品的准确名称,或者改用物品的系统ID(比如D&D 5e模块中,大治疗药水的系统ID为potion-of-greater-healing)进行匹配,避免名称大小写、翻译差异等问题:
let healthpotion = actor.items.find(item => item.system.id === "potion-of-greater-healing")
完整修正后的宏代码(含消耗逻辑)
main() async function main() { // 检查是否选中单个Token console.log("Tokens: ", canvas.tokens.controlled) if(canvas.tokens.controlled.length === 0 || canvas.tokens.controlled.length > 1){ ui.notifications.error("Please select a single token") return; } let actor = canvas.tokens.controlled[0].actor console.log(actor) // 查找大治疗药水 let healthpotion = actor.items.find(item => item.name === "Potion of Greater Healing") console.log(healthpotion) if(!healthpotion){ ui.notifications.error("No Health Potions left"); return; } // 执行药水消耗逻辑 if (healthpotion.system?.quantity) { // 堆叠物品:减少数量,数量为0时删除 await healthpotion.update({"system.quantity": healthpotion.system.quantity - 1}); if (healthpotion.system.quantity - 1 <= 0) await healthpotion.delete(); } else { // 非堆叠物品:直接删除 await healthpotion.delete(); } }
内容的提问来源于stack exchange,提问作者Dave Whitwell
相关产品推荐
相关产品推荐

