GetPlayers not working on server side script

◇◆丶佛笑我妖孽 提交于 2021-01-29 09:01:14

问题


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 :

  1. Server starts, number of players = 0
  2. Player joins, number of players = 1
  3. LocalScript runs - prints out the list of all 1 players

When you run this as a server Script, the flow of the game is :

  1. Server starts, number of players = 0
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!