#The best thing to do in a case like this is to just start from the beginning.
##I love functions.
They are awesome. They help organize your code and stops repetitive code. So let's start with creating a function along with creating a table to hold the players. However, I think an error may stem with holding a player type in a table, so I will just store their names there.
function RandomPlayer()
local holdPlayers = {}
end
Now let's go ahead and create a for loop to go through all of the players and add their names into the table.
function RandomPlayer()
local holdPlayers = {}
for _,v in pairs(game.Players:GetPlayers()) do
table.insert(holdPlayers, v.Name)
end
end
Alright. Now for the "hard" part. We will create a variable of a random number, much like you already did. We will also add the variable that holds the random player's name from the table.
function RandomPlayer()
local holdPlayers = {}
for _,v in pairs(game.Players:GetPlayers()) do
table.insert(holdPlayers, v.Name)
end
local randomNum = math.random(1, #holdPlayers)
local randomPlayerName = holdPlayers[randomNum]
end
Now to wrap it up is easy. We will use FindFirstChild to find the player, and then return it.
function RandomPlayer()
local holdPlayers = {}
for _,v in pairs(game.Players:GetPlayers()) do
table.insert(holdPlayers, v.Name)
end
local randomNum = math.random(1, #holdPlayers)
local randomPlayerName = holdPlayers[randomNum]
local randomPlayer = game.Players:FindFirstChild(randomPlayerName)
if randomPlayer then
return randomPlayer
else
return
end
end
######This has not been tested to work. I simply did all coding in the code block. Please be aware of any basic spelling errors in the script itself.
Here is the breakdown of a for loop:
Click here
The "_" is a variable that holds the 'key.' I did not have to use the 'key' variable so usually I just put an _ when I don't need it.
3 comments
Well yes, because thats the value it holds in the table. Try to print this: print(randomplayer[x].Name)
It prints "nil"
Mk. Give me a few minutes.