Roblox拳击脚本报错“Attempt to index boolean with 'Health'”修复求助
Roblox拳击脚本伤害失效与报错修复
问题原因
核心错误出在Touched事件的处理逻辑里:
local hum = hit.Parent:FindFirstChild("Humanoid") ~= Humanoid
这行代码把**比较结果(布尔值)**赋值给了hum变量,而不是获取被碰撞对象的Humanoid实例。当后续尝试访问hum.Health时,布尔值没有Health属性,直接触发Attempt to index boolean with 'Health'报错。
修复方案
先获取目标的Humanoid对象,再判断它不是当前玩家的Humanoid,同时确保对象存在。另外启用你定义的debounceDMG冷却变量,避免短时间内重复触发伤害。
修复后的完整代码
local rep = game:GetService("ReplicatedStorage") local debounceDMG = true rep.Combate.Soco.OnServerEvent:Connect(function(plr) -- 冷却判断,防止重复触发 if not debounceDMG then return end debounceDMG = false local mathRand = math.random(1,2) -- 避免覆盖全局math库 local char = plr.Character or plr.CharacterAdded:Wait() local playerHum = char.Humanoid local leftAnim = playerHum:LoadAnimation(script.Left) local rightAnim = playerHum:LoadAnimation(script.Animation) local hitbox = Instance.new("Part") hitbox.Parent = workspace hitbox.Transparency = 0 hitbox.Anchored = true hitbox.CanCollide = false hitbox.Size = Vector3.new(2.5,2.5,2.5) hitbox.CanTouch = true local connection = game:GetService("RunService").Heartbeat:Connect(function() if mathRand == 2 then hitbox.Position = char.LeftHand.Position else hitbox.Position = char.RightHand.Position end end) -- 播放对应拳击动画 if mathRand == 2 then leftAnim:Play() else rightAnim:Play() end hitbox.Touched:Connect(function(hit) -- 先获取目标Humanoid,再验证有效性 local targetHum = hit.Parent:FindFirstChild("Humanoid") if targetHum and targetHum ~= playerHum then targetHum.Health -= 5 end end) task.wait(.3) hitbox:Destroy() connection:Disconnect() -- 恢复冷却,时间可自行调整 task.wait(0.5) debounceDMG = true end)
额外优化说明
- 把变量
math改成mathRand,避免覆盖全局math库,防止后续调用math相关函数出错 - 给动画变量改名(比如
lanim1改成rightAnim),让代码逻辑更清晰 - 启用
debounceDMG冷却机制,避免玩家快速点击触发多次伤害 - 简化了Heartbeat里的条件判断,去掉冗余的elseif分支
内容的提问来源于stack exchange,提问作者takezo
相关产品推荐
相关产品推荐

