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

Choosing a random player?

I am making a hide and seek game. Someone has to be it, but my script won't work for it. I have a feeling it is an issue with the table, but I'm bad with them.

local contestants = {}

--while true do and other code

it = contestants[math.random(1, #contestants)]
print(it.Name)	

I get an error that says

ServerScriptService.MainScript:35: bad argument #2 to 'random' (interval is empty)

Thanks :)

2 answers

EDITED

The problem is, you're choosing from nothing. To fix this, just get all the players and choose from that.

Since you are using a table to pick from, you need to get all the players in the game and use 'table.insert' to insert the players you gathered into the table. But, you can do this another way. You can choose from players, the variable at the top. Do this by using the second script below.

CODES:

local contestants = {}
local players = game.Players:GetPlayers() --gets all the players

table.insert(contestants, players) --inserts the players into your contestants table

it = contestants[math.random(1,  #contestants)]
print(it.Name)  

local players = game.Players:GetPlayers() --gets all the players

it = math.random(1, #players) --do it this way because players isn't a table!
print(it.Name)  

1 comment

0

Thanks! Issue: it is spitting out nil at me.

local tab = {}

for a,b in pairs(game.Players:GetChildren()) do
table.insert(tab,b)
end

local randomPlayer = tab[math.random(1,#tab)]

There has to be at least one player in the game for it work or nil

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