Help with getting the player's char/hum?

Hey everyone, I’m trying to make an enemy AI that attacks the closest player. How would I get the player’s character/humanoid from a server script in the enemy? Here’s the code I have so far to do this:

-- Variables --
local PathfindingService = game:GetService("PathfindingService")
local body = script.Parent:WaitForChild("Torso")
local hum = script.Parent:WaitForChild("Humanoid")
game.Players.PlayerAdded:Connect(function(plr)
	local plrChar = plr.Character or plr.CharacterAdded:Wait()
    local plrHum = plrChar:WaitForChild("Humanoid")
end)

-- Enemy AI --
local attackPath = PathfindingService:CreatePath()
attackPath:ComputeAsync(body.Position, plrHum.position)

Is there only one player?
If there are multiple players, do you want the zombie to chase a random one, or the closest one.
Please be more specific

2 Likes

Ok, first you need a function to get the closest player to a given enemy. Then you can just computeAsync:

local function getClosestPlayer(zombie)
    local closest = math.huge
    for _, plr in ipairs(game.Players:GetPlayers()) do 
        local distance = (zombie.Position - plr.Character.HumanoidRootPart.Position).Magnitude
        if distance < closest then
           closest = distance
        end
    end
end

-- Enemy AI --
while task.wait() do
    local attackPath = PathfindingService:CreatePath()
    attackPath:ComputeAsync(body.Position, getClosestPlayer(body))
end

I haven’t worked with pathfinding service, so I don’t know how well this will run.

1 Like

ok thanks! I’ll try it out once I’m finished with the script