我正在尝试编写一个炮塔代码,当敌人进入炮塔射程时向敌人射击,但代码有时会中断并给出错误信息。Script:31: attempt to index nil with 'Humanoid'
这种情况很少发生,只有当僵尸死亡时才会发生。不仅如此,似乎有些子弹造成的伤害比实际伤害要大得多。
head = script.Parent.PrimaryPart
local function triggershoot(part)
local beam = Instance.new("Part",script.Parent)
beam.Anchored = true
beam.CanCollide = false
beam.Shape = "Block"
beam.CFrame = head.CFrame
beam.Size = Vector3.new(0.5,0.5,0.5)
beam.Material = "Plastic"
beam.BrickColor = BrickColor.new("Dark taupe")
beam.CFrame = CFrame.lookAt(head.Position,part.Position)
for i = 0, 50, 1 do
wait()
beam.CFrame = beam.CFrame + beam.CFrame.LookVector
beam.Touched:Connect(function(plr)
if plr.Parent:HasTag("enemy") then
plr.Parent.Humanoid:TakeDamage(3)
beam:Destroy()
end
end)
end
end
while true do
wait()
local parts = workspace:GetPartsInPart(script.Parent.zone)
for _, part in pairs(parts) do
if part:HasTag("enemy") and part.Parent.Humanoid.Health > 0 then
local update = CFrame.lookAt(head.Position,part.Position)
head.CFrame = update
coroutine.wrap(triggershoot)(part)
wait(1)
end
end
end
尝试将触摸事件函数移到 forloop 之外
如果我是正确的,那么您在脚本中遇到了两个主要问题:
发生此错误是因为
part.Parent.Humanoid
炮塔nil
尝试访问它。这通常发生在僵尸死亡时,其人形物体在炮塔检查其生命值或施加伤害之前被摧毁。解决方案:在尝试使用之前添加检查以确保 Humanoid 存在。
修改此部分:
对此:
您正在循环内连接 beam.Touched 事件,这意味着它会在每一帧中重复连接。这可能会导致子弹多次造成伤害。
解决方案:将 .Touched 事件移出循环,以便它只连接一次。
固定代码:
修复摘要:
Humanoid
存在(FindFirstChild("Humanoid"))
。.Touched
移出循环,以便每个项目符号仅连接一次。希望这能解决你们两个的问题!🚀