Hi, so I am trying to write a server script that will select a random player. It just comes up with this error: ServerScriptService.MainScript:16: invalid argument #2 to 'random' (interval is empty). I can’t figure it out. Please help. This is my script:
function ChoosePlayer()
if ChosenMode.Name == "Escape" then
RandomPlayer = GetPlayers[math.random(1, #GetPlayers)]
print("Gotten 1 Player: Escape")
elseif ChosenMode.Name == "Infection" then
RandomPlayer = GetPlayers[math.random(1, #GetPlayers)]
print("Gotten 1 Player: Infection, player can tag other players in")
elseif ChosenMode.Name == "DoubleTrouble" then
RandomPlayer = GetPlayers[math.random(2, #GetPlayers)]
print("Gotten 2 Players: DoubleTrouble")
end
end
When are you defining GetPlayers? If you call it the moment the server starts, it’ll automatically return back an empty table as Server Scripts run the moment a Server is first created (Or 0)
function ChoosePlayer()
local GetPlayers = game.Players:GetPlayers()
if ChosenMode.Name == "Escape" then
RandomPlayer = GetPlayers[math.random(1, #GetPlayers)]
print("Gotten 1 Player: Escape")
elseif ChosenMode.Name == "Infection" then
RandomPlayer = GetPlayers[math.random(1, #GetPlayers)]
print("Gotten 1 Player: Infection, player can tag other players in")
elseif ChosenMode.Name == "DoubleTrouble" then
RandomPlayer1 = GetPlayers[math.random(1, #GetPlayers)]
RandomPlayer2 = GetPlayers[math.random(1, #GetPlayers)]
print("Gotten 2 Players: DoubleTrouble")
end
end
I also edited it to where the second random player will not be the first random player with this line of code: repeat RandomPlayer2 = GetPlayers[math.random(1, #GetPlayers)] until RandomPlayer2 ~= RandomPlayer1
If I insert a Script either inside the workspace or ServerScriptService:
local Players = game.Players:GetPlayers()
print(#Players)
Sure the server would create, but no Players are actually in the server just yet
That’s because the Server is still trying to load everything that it needs to load (Server Scripts & Functions), you can actually check this by join your game, and refreshing the server list as it shows that there’s currently no players in the server just yet:
After everything has been properly loaded, then the Player joins the game & can play it
wait(10) --This is a delay to make sure that the Player is fully in the game
local Players = game.Players:GetPlayers()
print(#Players) -- Outputs back as 1
Got it! Thank you, I will create a script to where it uses an intermission for 30 seconds so all the players are properly loaded in. Then it will choose the gamemode and player(s) with no errors at all… Hopefully lol