Picking a random player error / problem!

Hi. I’m trying to make a minigame. But for some reason the code i use to pick a random player with. Is not working anymore. And i can’t find the error. By the way the error message is this: Assfg

And this is the code i use:

local Players = game.Players:GetPlayers()
local Randomplayer = Players[math.random(1, #Players)]

wait(2)

print(Randomplayer)

2 Likes

This means that #Players = 0 (so you have math.random(1, 0) and indeed the interval is empty because the min number is 1 and the max number is 0).
I suggest doing:

local Players = game.Players:GetPlayers()
local nplrs = #Players
local Randomplayer = nil
if nplrs > 0 then
     Randomplayer = Players[math.random(1, nplrs)]
end
10 Likes

The script probably runs before any players have joined the game. This means that that “Players” table is nil. If you put a wait before the first two lines instead of after then it should work in your test.

1 Like

No, this will not fix the problem because when the server starts the first player can be added with a delay and wait() will not help.

Thanks. This fixed it :smiley:!!

1 Like

I’m referring to his test not what the actual use would be of this since such information was not provided. But yes, of course, in a real situation you wouldn’t just put a wait infront of it. My bad on not making that clear.

1 Like

Tip: if you’re using math.random, passing a single argument will automatically set that number as the maximum of the interval or select the only element if there’s only one. The minimum will also implicitly be 1.

-- Use GetService, as it is canonical for fetching services!
local Players = game:GetService("Players"):GetPlayers()

local randomPlayer

if #Players > 0 then
    randomPlayer = Players[math.random(#Players)]
end
6 Likes