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

Choosing a random player?

Asked by 9 years ago

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

Log in to vote
1
Answered by
Relatch 550 Moderation Voter
9 years ago

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)  
0
Thanks! Issue: it is spitting out nil at me. secretassassin3 30 — 9y
Ad
Log in to vote
0
Answered by 9 years ago
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

Answer this question