Invalid argument #2 (string expected, got Instance)

This is the error I get in output when I run this script.
I don’t know what could be the problem. I’m trying to make a script that finds the closest player.

local Players = game:GetService("Players")

local part = script.Parent.HumanoidRootPart

local maxDistance = math.huge

while true do
	wait(1)
	local nearestPlayer, nearestDistance
	for _, player in pairs(Players:GetPlayers()) do
		local character = player.Character
		local distance = player:DistanceFromCharacter(part.Position)
		if not character or 
			distance > maxDistance or
			(nearestDistance and distance >= nearestDistance)
		then
			continue
		end
		nearestDistance = distance
		nearestPlayer = player
	end
	print("The nearest player is ", nearestPlayer)
	
	if nearestPlayer ~= nil then
		local plr = workspace[nearestPlayer].Name -- Error here
		script.Parent.Humanoid:MoveTo(plr.HumanoidRootPart.Position)
	end
	
end
1 Like

try this:

local plr = workspace[nearestPlayer.Name]
1 Like

Also- a tip:

Dont use Wait(), its deprecated.

Use task.wait() instead.

1 Like

Thank you! It works better now!

1 Like
local nearestPlayerName = nearestPlayer.Name

They could also just index the nearest player’s “Name” property.