Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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)]

2 comments

0

I hope this helped :)

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!

This discussion is preserved as it was. New answers, comments, and votes are closed.