I have a script which is supposed to stop firing when the NPC goes out of range, but it doesn’t work, it keeps firing when it goes out of range
local NPC = false
local Unit = script.Parent.Torso.Position
local Target = game.Workspace.Dummy.Torso.Position
local distance = (Target - Unit).Magnitude
while true do
if distance < 40 then
NPC = true
else
NPC = false
end
while NPC == true do
game.ServerStorage.Bullet:Clone().Parent = game.Workspace
wait(1)
end
wait(0.1)
end
It’s because the distance is called outside of the loop. So it gets the distance at first, then it stays the same no matter what. Fix this with this:
local NPC = false
while true do
local Unit = script.Parent.Torso.Position
local Target = game.Workspace.Dummy.Torso.Position
local distance = (Target - Unit).Magnitude
if distance < 40 then
NPC = true
else
NPC = false
end
while NPC == true do
game.ServerStorage.Bullet:Clone().Parent = game.Workspace
wait(1)
end
wait(0.1)
end
You’re only calculating the distance once, when the script first executes, you need to move local distance = {calculation here} so that it’s inside the loop.