Roblox游戏矿石售卖功能失效:现金未增矿石未清零求助
Roblox挖矿游戏售卖脚本修复方案
问题根源分析
你的脚本存在几个关键问题,导致售卖逻辑不执行:
- 无nil校验:当触发
Touched的不是玩家角色(比如矿石、工具),game.Players:GetPlayerFromCharacter(hit.Parent)会返回nil,后续操作player.leaderstats会直接报错中断代码 - 未确认统计对象存在:如果
leaderstats、Cash或Ore实例未正确创建,访问它们的Value属性也会报错 - 触发范围太宽泛:任何触碰售卖部件的对象都会触发事件,容易引发误操作或报错
修复后的脚本
local db = false -- 防重复触发 script.Parent.Touched:Connect(function(hit) -- 只处理玩家角色的触碰,优先检测Humanoid local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid") if not humanoid then return end local player = game.Players:GetPlayerFromCharacter(hit.Parent) -- 确认玩家存在且leaderstats相关对象齐全 if not player or not player:FindFirstChild("leaderstats") then return end local cash = player.leaderstats:FindFirstChild("Cash") local ore = player.leaderstats:FindFirstChild("Ore") if not cash or not ore then return end if not db then db = true -- 更新现金与矿石数量 cash.Value += ore.Value ore.Value = 0 task.wait(1) db = false end end)
关键修复说明
- 新增
Humanoid检测:确保触发事件的是玩家角色,过滤掉其他无关对象 - 逐层nil校验:依次确认玩家、leaderstats、Cash、Ore实例存在,避免报错中断代码
- 使用
task.wait()替代wait():Roblox推荐使用更高效的task库函数 - 简化数值更新语法:用
+=替代传统的赋值写法,更简洁
内容的提问来源于stack exchange,提问作者SFS Perseverance
相关产品推荐
相关产品推荐

