Checking if player has character doesn't work

while wait() do
	local pla = game.Players:GetChildren()
	local a = pla[1]
	for i,v in pairs(pla) do
		if v.Character then
			local ti = (a.Character.HumanoidRootPart.Position-script.Parent.Position).Magnitude
			local te = (pla[i].Character.HumanoidRootPart.Position-script.Parent.Position).Magnitude
			
			if te<ti then
				a=pla[i]
			end
		end
	end
	if a.Character then
		print(a.Name)
	end
end

In if a.Character then it doesn’t work and it says
17:30:03.141 - Workspace.FBXImportGeneric.Cube.Script:14: attempt to index nil with ‘Character’

Because when the script first starts running, there are no players in game. So pla[1] is nil.

1 Like

Ok ,.

The problem is that scripts run before the player even loads. Another person who explains how to get around this pretty well this sleitnick
https://www.youtube.com/watch?v=bX8MxozRTGo

Roblox has built-in events which can be used “exactly” for that. Such as PlayersFolder.PlayedAdded, and PlayerIstance.CharacterAdded.

In addition to that, I suggest using GFink’s Catch All PlayerAdded.

2 Likes