So for the system I’m doing, I have to get half of the players in-game. How would I do this? All I know is that I would have to use some sort of table and loop through the players.
local half = {}
local otherHalf = {}
for _, v in pairs(game.Players:GetPlayers()) do
-- ???
end
Even though this might not be the most efficient way here it goes.
First of all, we are going to get all the players.
local Players = game:GetService("Players") --//Gets the Players
And then start setting up a for loop so you can get the players
local ChosenPlayers = {} --//A table containing chosen players
for i = 1, #Players/2, 1 do --//Setting a for loop which is supposed to run the code block written below amount of Players / 2 times
local RandomNumber = math.random(1,#Players) --//Getting a random number from 1 to amount of players
local Player = Players[RandomNumber] --//Getting the player with the random number from the Players table
table.remove(Players, RandomNumber) --//Removing the chosen player from our players table
table.insert(ChosenPlayers,Player) --//Adding the chosen player into a table which we will store all the chosen players in
end
local players = game:GetService("Players")
for i, player in pairs(players:GetPlayers()) do
if i % 2 == 0 then --checks if player number is divisible by 2 without a remainder
--do something with player
end
end
Much simpler & more efficient way of producing the same behavior.
local players = game:GetService("Players")
local playerList = players:GetPlayers()
for i = 1, #playerList/2 do
local rand = math.random(1, #playerList)
local plr = playerList[rand]
--do stuff with player
end
I get you want less lines of code however how are you gonna store the chosen half of the players? And how are you gonna stop it from chosing the same person over and over again?
local Players = game:GetService("Players")
local Half_1 = {}
local Half_2 = {}
local Half = 1
for _, player in pairs(Players:GetPlayers()) do
if Half == 1 then
table.insert(Half_1, player)
Half = 2
elseif Half == 2
table.insert(Half_2, player)
Half = 1
end
end
edit: I have a feeling I know what you are trying to do