Math.random(game.Players:Getplayers(random)
im fairly new to scripting :/ and im just testing out to make a game. I dont understand alot so if i could get a bit of feed back it would help :) im trying to get it to get 1 random player to be chosen.
As far as I can see, the only errors I see are syntax errors. Let's walk through the whole process shall we?
:GetPlayers()
The :GetPlayers()
method returns a table full of all the players in the game at the time the method was called. You call the method on the Players service, and you should store the table into a variable, like so:
local Players = game.Players:GetPlayers()
#
The #
operator is used to return the length of a table or of a string. Basically, it returns the number of elements in a table, or the number of characters in a string. In our case, we're going to use it on the Players
table to get how many players are in the game by getting how many elements are in the table, like so:
local NumPlayers = #Players
math.random()
The math.random()
function generates a random integer between 2 given numbers, or between 0 and 1 given number, or a floating point number between 0 and 1 if no parameter is given. In our case, we're going to generate a random number between 1 and the number of players in the game, like so:
local RandomPlayerIndex = math.random(1, NumPlayers)
[]
The []
operator is used to get a specific element from a table with a given index between the brackets. So if you wanted to get the 2nd element in a table, you'd say Table[2]
. In our case, we're going to get the random player by using the operator on the Players
table and using the RandomPlayerIndex
variable in the brackets, like so:
local ChosenPlayer = Players[RandomPlayerIndex]
So, the full code should be
local Players = game.Players:GetPlayers() local NumPlayers = #Players local RandomPlayerIndex = math.random(1, NumPlayers) local ChosenPlayer = Players[RandomPlayerIndex]
The ChosenPlayer
variable will contain the randomly chosen player
Hope this helped!
EDIT
Here's the cleaned code
local Players = game.Players:GetPlayers() local ChosenPlayer = Players[math.random(1, #Players)]
This code works exactly like the code above, except that everything is more compact.
If you don't care about weight, or if you pick the same player more than once use this:
math.randomseed(tick());math.random() --We use randomseed to seed the generator so we don't get the same numbers in everyserver. function pickRandomPlayer() local plrs = game.Players:GetPlayers() return plrs[math.random(1,#plrs) end