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.
4 comments
Creating a NumPlayers variable is redundant. Using #Players inline would work. You kind of just bloated most of that code.
I did that just to show the different parts of the code needed for it to function and put them all on their own line. I'll add in the cleaned code as an edit
thx but i keep getting this error: Workspace.Script:6: bad argument #2 to 'random' (interval is empty)
@ioutrageous That happens when the 2nd parameter in the math.random() function is less than the 1st one. If there are 0 players in the game, then it will error because that's like saying math.random(1, 0)