I'm making a cannon that targets the NPC, and damages the NPC over time. Here's the script:
a = script.Parent
local cbest = 1000
besti = game.Workspace.Units.back--Furthest block from point (purposely set)
for i,v in ipairs(game.Workspace.Units:GetChildren("Warrior")) do --Finds all parts in "Units" named "Warrior"
local p = (v.Parent.Warrior.Torso.Position-a.Position).magnitude
if cbest > p then
cbest = p
besti = v
end
end
print(besti)
while true do
wait(3)
besti.Humanoid.Health = besti.Humanoid.Health - 2 --Hurts closest found Humanoid
end
w = besti.Humanoid
w.Changed:connect(function()
if w.Health <= 0 then
game.ReplicatedFirst.Attack:Clone().Parent = script.Parent --Deletes this script, and copies -it again from ReplicatedFirst so that the process can be repeated (If their are multiple enemies)
script:Destroy()
end
end)
The problem is that it keeps selecting the part "back". Now, the purpose of "back" is to set the furthest possible point that the NPCs can be, that way it can create a boundary without going over ROBLOXs "no further than 1000 studs rule" with Magnitude. "v" is supposed to be an NPC "warrior" selected from the holding model "Units". However, it appears that "v" is not selecting any warrior to become "v", instead it is remaining blank. So, when it comes time for "besti" (which is supposed to be the closest NPC) to be determined and have health removed from it, "besti" is still "back", as "besti" is also used to determine "back" earlier in the script.
I've been trying to figure out whats wrong for hours now, and I feel like its something so stupidly obvious, and I'm just blind.
Any help?

1 comment
1000 studs is a distance limit for raycasting calculations so the engine doesn't have to do so much math when a ray never hits something.