NPC follow script not working

I made a script that should make the NPC follow anything with a humanoid in it (because my game has models that need to be followed as well) but when I run the script, the NPC’s humanoid WalkToPoint turns to 0,0,0 which I don’t know why and makes the NPC walk off the map.

Images

image

image

Source code:

local players = game:GetService('Players')
local zombie = script.Parent
local humanoid = zombie:FindFirstChildOfClass('Humanoid')

function walk()
	while wait() do
	for i,v in pairs(workspace:GetDescendants()) do
		if v:IsA('Humanoid') and v.Parent:FindFirstChild('HumanoidRootPart') then
			local c = v.Parent
			local hrp = c.HumanoidRootPart
				humanoid.WalkToPoint = Vector3.new(hrp.Position)
			end
		end
	end
end

players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(walk)
end)

(I did search but did not find anything that helped me and it normally had a distance limit.)

Also nothing is in the output.

1 Like

Your almost there, you assigned its place to go with walto point but now you need to call the MoveTo() function to humanoid

1 Like

Thank you for your reply, but why does it get set to 0,0,0 in the first place?

Change

humanoid.WalkToPoint = Vector3.new(hrp.Position)

to

humanoid:MoveTo(hrp.Position)

Also your code has a memory leak and overall bad practice, this will crash your server if your map is big and there are more than 5 players. Even lower than 5 players it will lag a lot.

1 Like

Thank you! It works! If the while wait() do part is why it is bad practice, i’ll change it to while true do wait(1) so it will be less laggy.

You don’t need the function “walk”, and you don’t need to connect it to the player added event.

Just move the while loop outside the function and remove the function and the connections.

And instead of looping through workspace, loop through the Player list, Players:GetPlayers(). To get the character do v.Character.

2 Likes