Alright, hello everyone. This is a common question usually asked here on this website. I've been messing with this and it always shows this error: "ServerScriptService.Script:13: bad argument #2 to 'random' (interval is empty)"
This is the code which contains the line of code and the locals used:
local players = game.Players:GetChildren() local randomplayer = players[math.random(1,#players)] --This is line 13 in my script
This is the only error, if you can help that would be appreciated. ;) ~Spooksletsky @Spooksletsky
You should use the method GetPlayers()
rather than GetChildren()
incase there is a child of game.Players
that is not a player:
local players = game.Players:GetPlayers() if #players > 0 then local randomPlayer = players[math.random(1, #players)] -- Do Stuff end
All this error means is that #players
equals zero. No players are in the game.
I don't know the context of these lines, but it might be that they're running as soon as the game starts. This would mean that no players are loaded yet, making the table empty. You can fix this with either a loop or an event depending on the situation.
repeat wait(1) until #game.Players:GetPlayers() > 0
Or,
game.Players.PlayerAdded:connect(function(plr) --do stuff end)
And as other people have pointed out, definitely use GetPlayers
.
Here's one that I'm using For my game and it works.
local randomplayer = {} local x local T = game.Workspace.WaitTime.Value game.Players.PlayerAdded:connect(function() -- What you're doing wrong is that you're making a table with no players even loaded. Doing it this way it will Update the table everytime a player joins. local players = game.Players:GetPlayers() ------------------------------------------------------- -- Ignore This VV. But you can use it if you want. for _, v in pairs (players) do table.insert(randomplayer, v.Name) end while wait(5) do local randomnum = math.random(#randomplayer) local randomname = randomplayer[randomnum] local randomplayer = game.Players:FindFirstChild(randomname) if randomplayer then print(randomplayer) game.Workspace.TheChosenOne.Value = randomplayer end end end)
The problem with your script is that the table is empty and scripts always run before the character is even loaded so you make the script wait with the:
game.Players.PlayerAdded:connect(function() local players = game.Players:GetPlayers() end)