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

Why is the "player" returning as nil?

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?

2 comments

0

What line is the error showing at?

0

line 34, when i try to print the value of the player

1 answer

✓ Accepted answer

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

5 comments

0

Thanks, it worked!

0

Actually uh, character has turned into nil... It worked when i first tested it

0

Sometimes it works, sometimes it doesnt, ill add a waitforchild

0

If so, then you might want to try adding player.CharacterAdded:Wait() in front of the char variable.

0

Or just change the variable to local char = player.Character or player.CharacterAdded:Wait(), that should work too.

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