local pf = Instance.new("Folder"); pf.Name = "PlayerFolder"; pf.Parent = workspace; local parentorso = script.Parent.Torso; local h = script.Parent.Humanoid; local dist = 20 local function sortplayers(player) player.CharacterAdded:Connect(function(character) character.Parent = pf; end) end local follow local function GetNearestPlayer(WorldPos) for _,player in pairs(pf:GetChildren()) do if player.HumanoidRootPart then if player.Humanoid.Health > 0 then local distance = (player.HumanoidRootPart.Position - WorldPos).Magnitude if distance >= 20 then dist = distance follow = workspace[player].Torso print(player.Name) return player; end end end end end while true do wait(1) GetNearestPlayer() print(follow.Parent.Name) end game.Players.PlayerAdded:Connect(sortplayers) local pfs = game:GetService("PathfindingService"); local path = pfs:FindPathAsync(parentorso,follow); local points = path:GetWaypoints(); if path.Status == Enum.PathStatus.Success then for i,v in pairs(points) do h:MoveTo(v.Position) h.MoveToFinished:Wait() if v.Action == Enum.PathWaypointAction.Jump then h.Jump = true end end end
I am trying to make a script that makes a NPC walk towards the nearest player. Unfortunately, the player keeps returning as nil?
Instead of putting player's character into a folder, you could use the game.Players:GetPlayers() function in here. I'm not sure if it will fix, you might need to edit my script here a bit, but at least that's how I would do it.
local function GetNearestPlayer(WorldPos) for _,player in pairs(game.Players:GetPlayers()) do local char = player.Character if char.Humanoid.Health > 0 then local distance = (char.HumanoidRootPart.Position - WorldPos).Magnitude if distance >= 20 then dist = distance follow = workspace[player].Torso print(player.Name) return player; end end end end