Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Random player picker works when there's only one player, but errors when there's multiple?

Asked by 5 years ago

I'm trying to make a round system that'll randomly pick a player for a role, it does work when there is only one player, but fails when there are multiple players.

Snippet:

local RandomPlayer = game.Players:GetChildren()[math.random(1,#game.Players:GetPlayers())]
            if RandomPlayer.Team.Name == "Lobby" then
                RandomPlayer.TeamColor = BrickColor.new("Lapis")
                RandomPlayer.Character:WaitForChild("Humanoid").JumpPower = 0
                workspace.OfficeChair.Seat:Sit(RandomPlayer.Character:WaitForChild("Humanoid"))
                game.ReplicatedStorage.NightGuardLocal:FireClient(RandomPlayer)
            end

Output:

21:59:41.895 - ServerScriptService.Script:18: bad argument #2 to 'random' (interval is empty)
21:59:41.907 - Stack Begin
21:59:41.908 - Script 'ServerScriptService.Script', Line 18
21:59:41.908 - Stack End

1 answer

Log in to vote
1
Answered by
EthanFins 104
5 years ago

if your trying to make a script that picks a random player I wouldn't do it using remove functions? I would do it in the main game loop if you're doing a mini game or mini game mechanics. What you would want to do is something more like this :

local PlayerTable = {}

for i,player in pairs(game.Players:GetPlayers()) do
    table.insert(PlayerTable,player.Name)
end

local RandomPlayer = game.Players:FindFirstChild(PlayerTable[math.random(1,#PlayerTable)])

What this dose is it will get all the players in the game and put them in a table. Then it will get one random player using > math.random(1,#PlayerTable)]

0
I hope this helped :) EthanFins 104 — 5y
0
Not sure if I wasn't waiting long enough, or if this just fixed the issue. (I was waiting 1 second), but either way thanks for the help! CaptainAlien132 225 — 5y
Ad

Answer this question