Get random player

Im trying to get a random player, I swear this used to work.

2 Likes
function lib.Select()
    local Players = game:GetService("Players"):GetPlayers()
    local RandomPlayer = math.random(1, #Players)
    return RandomPlayer
end

Make sure to add a starting number before #Players!

1 Like
function lib.Select()
    local players = game.Players:GetPlayers()
    return players[math.random(1,#players)]
end
1 Like

If the function only finds one value, it will automatically set it as max and default minimum as 1. (This is kinda a undoccumented thing that just exists)

1 Like

That’d error “math.random(1, #Players) is not a valid member of Players”, wouldn’t it?

1 Like

Same issue, interval is empty. Note the function above it right now is jut printing the result meaning it’d have no effect on it. This has really got me scratching my head.

1 Like

The only other thing I can think of is your 2nd number is 0 or nil.

If the minimum is bigger than the maximum, it will throw this error. Those are the only 2 explanations.

Now that I think about it, there’s no value between the number of players and the number of players, so you have to do 1, #Players. If the lower number is more or equal to the higher number, theres no value in between, throwing the error. @FordNGuns

1 Like

Is it because whenever you run that function, the maximum value, which in this case is the number of players, is 0 because the player haven’t loaded in yet?

1 Like

I didn’t even think of that, let me attempt to fire it after doing a player added function…

and that was it… well then I think I need a break from coding for the day.

1 Like

I’m going to say this once again just to clear up confusion. You do not need the 1. Roblox will automatically fill the empty value with a 1. Instead my issue was I was firing before any players were actually added, meaning it had nothing to select from.

1 Like

That only returns a number though.

1 Like

What I’m saying is without a value between, there’s no value to choose from (except from the value given).

If the first number is BIGGER than the second, it won’t work either, causing the error.

1 Like

I believe not, It’s math.random(1, #Players). :slightly_smiling_face:

Edit: Nevermind, you’re right. I should stop for the night, lol. :joy:

1 Like

Yes. Let’s say there are 5 players in game. The code would substitute to:

math.random(1, 5)

Which returns a number. Instead, you need to index the Players using the number found with math.random. Just a small mistake :slight_smile:

1 Like