What is wrong with this Follow player script?

I do not know what is wrong with this script. I’ve been simplifying it and expanding it for over two days and I have no idea what is wrong with it. No errors also appear in the output as well. Please help

local PathfindingService = game:GetService("PathfindingService")
local human = script.Parent:WaitForChild("Zombie")
local torso = script.Parent:WaitForChild("Torso")

 
local function FindHumanoid()
	local target = nil
	for i,v in pairs(game.Workspace:GetChildren()) do
		local humanoid = v:FindFirstChild("Humanoid")
		local RootPart = v:FindFirstChild("UpperTorso")
		if humanoid and RootPart and v ~= script.Parent and humanoid.Name ~= "Zombie" then
			target = RootPart
		end
	end
end

while wait(0.1) do
	local Find = FindHumanoid()
	if Find and script.Parent.State ~= "Grab" then
		local Path = PathfindingService:CreatePath()
		Path:ComputeAsync(torso.Position, Find.Position)
		local waypoints = Path:GetWaypoints()
		for i, waypoint in pairs(waypoints) do
			human:MoveTo(waypoint.Position)
			human.MoveToFinished:Wait(0.1)
		end
		
		human:MoveTo(Find.Position)
	end
end

Here you are expecting the function FindHumanoid to return something. But the function does not return anything. Thus, you have to add a return to your function. Here is an example:

local function FindHumanoid()
	local target = nil
	for i,v in pairs(game.Workspace:GetChildren()) do
		local humanoid = v:FindFirstChild("Humanoid")
		local RootPart = v:FindFirstChild("UpperTorso")
		if humanoid and RootPart and v ~= script.Parent and humanoid.Name ~= "Zombie" then
			target = RootPart
            return target
		end
	end
end

Also may I add, your code does not function that well, it is not that effective. I recommend you search up a tutorial on Youtube on “How to make a zombie AI”. I do not mean this in a rude way, I’m just trying to help you :slight_smile:

Things you can improve or add:

  1. Finding the nearest HumanoidRootPart
  2. Calling the function less often
  3. Detect when the Zombie’s path is blocked

Anyways those are just a few things you can improve or add to your code. There are many tutorials out there. Good luck.

Yeah I might add those suggestions you asked and I’ve also seen the video. I was just trying to figure out how to use pathfinding service. Thanks for the help!

1 Like