I'm trying to code a turret, shooting enemies when it gets in the range of the turret, and the code sometimes breaks giving me the error Script:31: attempt to index nil with 'Humanoid'
This happens rarely and only does so when a zombie dies.
Not only that but it seems some of the bullets created seem to make way more damage than they really should.
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
try moving the touch event function outside the forloop
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)
beam.Touched:Connect(function(plr)
local char=plr.Parent
local hum=char and char:FindFirstChildOfClass"Humanoid"
if char:HasTag("enemy") then
hum:TakeDamage(3)
beam:Destroy()
end
end)
for i = 0, 50, 1 do
wait()
beam.CFrame = beam.CFrame + beam.CFrame.LookVector
end
beam:Destroy()
end
while true do
wait()
local parts = workspace:GetPartsInPart(script.Parent.zone)
for _, part in ipairs(parts) do
local h=part.Parent;h=h and h:FindFirstChildOfClass"Humanoid"
if part:HasTag"enemy"and h and h.Health > 0 then
local update = CFrame.lookAt(head.Position,part.Position)
head.CFrame = update
coroutine.wrap(triggershoot)(part)
wait(1)
break
end
end
end