Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 2 years ago
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

Log in to vote
0
Answered by
enes223 327 Moderation Voter
2 years ago
Edited 2 years ago
  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

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" Dinoboshoff1 -17 — 2y
0
Ah sorry, editing my answer now enes223 327 — 2y
Ad

Answer this question