so im making a tower defense game, but when i saw the tower attack, it killed multiple enemies at once, i tried making it so it keeps killing the same enemy until its dead, but, i got the error:
Attempt to index nil with "Position"
here is the code that makes the tower attack:
repeat
wait(firerate)
script.Parent.Parent.CFrame = CFrame.new(script.Parent.Parent.Position,v.PrimaryPart.Position)
Attack(v)
until not v
A possible issue is that your code checks if v still exists, then there is a delay before it tries to get it’s position. Which means v could no longer exist after the delay, so it can’t get it’s position.
Instead, try placing the delay at the end of your repeat loop:
repeat
script.Parent.Parent.CFrame = CFrame.new(script.Parent.Parent.Position,v.PrimaryPart.Position)
Attack(v)
wait(firerate) -- Delay at end here, then check if v still exists
until not v
local range = script.Parent.Configuration.Range.Value
local damage = script.Parent.Configuration.Damage.Value
local enemies = game.Workspace.Enemies
local idleAnim = script.Parent.Humanoid.Animator:LoadAnimation(script.Parent.Idle)
local shootAnim = script.Parent.Humanoid.Animator:LoadAnimation(script.Parent.Shoot)
local firerate = script.Parent.Configuration.Firerate.Value
idleAnim:Play()
coroutine.wrap(function()
while true do
range = script.Parent.Configuration.Range.Value
damage = script.Parent.Configuration.Damage.Value
firerate = script.Parent.Configuration.Firerate.Value
wait()
end
end)()
function Attack(target)
idleAnim:Stop()
spawn(function()
shootAnim:Play()
target.Health.Value -= damage
script.Pistol:Play()
shootAnim.Stopped:Wait()
idleAnim:Play()
end)
end
function Look()
for i,v in pairs(enemies:GetChildren()) do
if v then
if v:IsA("Model") then
if v and (v.PrimaryPart.Position - script.Parent.PrimaryPart.Position).Magnitude <= range/1.5 and v.Dead.Value == false then
print(v ~= nil) -- prints true if v exists, false if not
repeat
print(v ~= nil) -- prints true if v exists, false if not
script.Parent.Parent.CFrame = CFrame.new(script.Parent.Parent.Position,v.PrimaryPart.Position)
Attack(v)
wait(firerate)
until not v
else
--enemy is dead so no code should be run
end
end
end
end
end
while true do
Look()
wait(firerate)
end