Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

FindNearestPlayer is not a valid member of Players "Players". can somebody help?

Me again lol. So i'm trying to make this game where an npc follows the player but i'm having trouble getting the NPC to find the player and go towards it. No matter what i do the error on title always appears and i can't seem to find the problem. I'd really appreciate some help. Here's the code. Thanks in advance. By the way, it redirects to line 5.

local NPC = game.Workspace:FindFirstChild("Builder Dude")
local humanoid = NPC:WaitForChild("Humanoid")

while true do
	local nearestPlayer = game.Players:FindNearestPlayer(NPC.HumanoidRootPart.Position)
	if nearestPlayer then
		humanoid:MoveTo(nearestPlayer.Character.HumanoidRootPart.CFrame)
	end
	wait(1)
end

1 answer

Players does not have a FindNearestPlayer method, you will have to code such a function yourself

P.S Humanoid:MoveTo accepts a Vector3, you have supplied it nearestPlayer.Character.HumanoidRootPart.CFrame

example script

local Players = game:GetService("Players")

local function GetNearestPlayer()
	local ClosestPlayerCharacter
	local ClosestPlayerMagnitude = math.huge --This serves as the max range the NPC can find a target
	
	for _,Player in Players:GetPlayers() do
		local PlayerCharacter = Player.Character
		local PlayerHumanoidRootPart
		
		if PlayerCharacter then
			PlayerHumanoidRootPart = PlayerCharacter:FindFirstChild("HumanoidRootPart")
			if not PlayerHumanoidRootPart then
				continue
			end
		else
			continue
		end
		
		local PlayerMagnitude = (NPC.HumanoidRootPart.Position - PlayerHumanoidRootPart.Position).Magnitude
		if PlayerMagnitude < ClosestPlayerMagnitude then
			ClosestPlayerMagnitude = PlayerMagnitude
			ClosestPlayerCharacter = PlayerCharacter
		end
	end
	
	return ClosestPlayerCharacter
end

This discussion is preserved as it was. New answers, comments, and votes are closed.