问题
I am learning lua making games in Roblox. I have this sample of code that I got from their developer website.
Players = game:GetService("Players")
for i, player in pairs(Players:GetPlayers()) do
print(player.Name)
end
This code works when I paste it in a local script but it doesn't when I paste it in a server side script. I don't get an error, but nothing gets printed. I am wondering why this is, and also what code do I need to use to get all players from a server side script. Thanks
Edit --------------------------------------------------
I have also tried to run this code both on a server side script and a local script:
local players = game.Players:GetChildren()
print(typeof(players))
When this code is running on a local script, it comes back with: table. I got nothing when I run it on a server side script. Is this normal?
回答1:
I believe you have a timing issue. When you run this as a LocalScript, the flow of the game is :
- Server starts, number of players = 0
- Player joins, number of players = 1
- LocalScript runs - prints out the list of all 1 players
When you run this as a server Script, the flow of the game is :
- Server starts, number of players = 0
- Script runs - prints out the list of all 0 players
If you were to modify your example to be something like this:
Players = game:GetService("Players")
print(string.format("Listing all %d player names :", #Players:GetPlayers()))
for i, player in pairs(Players:GetPlayers()) do
print(i, "- ", player.Name)
end
print("Done listing names")
You should expect to see this in the output :
Listing all 0 player names :
Done listing names
来源:https://stackoverflow.com/questions/59697101/getplayers-not-working-on-server-side-script