I need help with tables and math.random. I want to create a script that choose a random player at a given time. Also I want to get the random player's name and give tools to that random player. Also when i get a random player it prints out table:02342DSF <-- that was made up but things like that get printed in the output.
Here's what I got:
local players = game.Players:GetChildren() local name = players.Name local randomplayer = {} local x game.Players.PlayerAdded:connect(function() local players = game.Players:GetPlayers() table.insert(randomplayer,players) while wait(3) do x = math.random(#randomplayer) print(randomplayer[x]) end end)
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
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.