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:
And this is the code i use:
local Players = game.Players:GetPlayers()
local Randomplayer = Players[math.random(1, #Players)]
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
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.
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.
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