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

getPlayers not working on server-side script?

Why does this code work on a local script but not a server-side script?

local Players = game:GetService("Players")

for i, player in pairs(Players:GetPlayers()) do
    print(player.Name)
end

2 answers

✓ Accepted answer

its not working because "Players" is just a folder type thing that holds all the local players profiles inventory and stuff.. to get a player you would normally do local plr = game.Players.LocalPlayer but that doesn't work in server scripts only in local scripts so what you would have to do instead is.

game.Players.PlayerAdded:connect(function(player)
	--your code
end)

when you do this you get the player value and then you can use it. and if you want to get the Character you can either do local char = player.Character or

player.CharacterAdded:connect(function(character)
	
end)

this would go after the function to get player so it would look like:

game.Players.PlayerAdded:connect(function(player)
	player.CharacterAdded:connect(function(character)
		--your code
	end)
end)

anyway hope this helped you and your welcome :)

What my comrade said was correct but let me format some more stuff into a more descriptive touch..

Adding a Trigger...

So, for a script to run correctly... you should always have a statement that checks to see if a value is correct for a script to run.

Your mistake

Your script if it was to work would get all the players names at once and print them consistently which that will crash/break your game if it worked.

Always add a wait(0.1)

If you don't add this, you will consistently be running this script and in some scenarios, this can crash the script as of what we call a Script Time Out. So, i'd always add a wait, just to be safe.

How it should be scripted

You don't need the variable for player as you can just have it connect and print the players name when they are added, you can also add to these values if you put two dots and then "a value in these quotation marks."

--[[Made By MillerrIAm]]--
--[Main Script]
game.Players.PlayerAdded:Connect(function(player)
	print(player.Name.." joined.")
	wait(0.5)
end)

If this answers your question, mark it as the solution!

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