Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

NPC that goes to the closest blocks, my script not working for some reason?

local NPC = script.Parent
local humanoid = NPC.Humanoid
local Doors = game.Workspace.DoorTarget

for i, door in ipairs(Doors) do
	local distance = (NPC.PrimaryPart.Position - door.Positon).magnitude
	if distance < maxDistance then
		nearestDoor = door
		maxDistance = distance
	end
end

if nearestDoor then
	humanoid:MoveTo(nearestDoor.Position)
end

Hi All,

I have made this script above, basically I have an NPC that needs to go to the closest "DoorTarget" block, and once done should go to the next closest "DoorTarget" and this should this continue. The max distance needs to be 20

For some reason this script doesn't want to work, please let me know if you can find this issue.

FYI: I just place this script inside my NPC

Thanks in advance all..

1 answer

✓ Accepted answer
  1. There is no max distance variable
  2. You need to loop the script

If you don't loop the script after it's done moving or not found a door, it won't work as you expect and also you need to wait for the move to to finish before repeating because it can do things like switching doors while moving to another door, script (edited because I missed something):

local NPC = script.Parent local humanoid = NPC.Humanoid local maxDistance = 20 local Doors = game.Workspace.DoorTarget

while task.wait() do for i, door in ipairs(Doors:GetChildren()) do local distance = (NPC.PrimaryPart.Position - door.Positon).magnitude if distance < maxDistance then nearestDoor = door maxDistance = distance end end

if nearestDoor then
    humanoid:MoveTo(nearestDoor.Position)
	humanoid.MoveToFinished:wait()
end

end

2 comments

0

Thanks for the response, I seem to be getting this error? " 01:56:31.690 Workspace.NPC.Script:7: invalid argument #1 to 'ipairs' (table expected, got Instance) - Server - Script:7"

0

Ah sorry, editing my answer now

This discussion is preserved as it was. New answers, comments, and votes are closed.