What is wrong with this Code? I saw this Code in a Forum but it wont work (The Shuffle Part is not working).
I want when Players are joining in a Private Server, they are added in 2 Teams (tables) When 9 Players are in the Game it will be 4 VS 5 (It will be a FPS Game) When its 8 Players it will be 4 VS 4 and when its 10 Player it will be 5 vs 5. One Problem: When 8 Players are joined but 2 Players are loading to the Place, the 8 Players are added in the Teams and it will be 4 VS 4 but the other two players that added a few seconds after they are not added to the team because the game just see 8 players first… I need help with this
local players = {}
local one_team = {}
local two_team = {}
for i,v in pairs(game.Players:GetPlayers()) do --Insert current players to table
table.insert(players, v.Name)
end
local randomPlayers = shuffle(players) --Randomize players table
for i = 1, math.ceil(#randomPlayers/2) do --Take half of the random players and put them into team 1
table.insert(one_team, randomPlayers[i])
table.remove(randomPlayers, i)
end
for i, v in pairs(randomPlayers) do --Put the rest of the players into team 2
table.insert(two_team, v)
end
randomPlayers = {} --Reset table
Assuming your problem is that new players aren’t being sorted to teams but existing players are, you would need a PlayerAdded connection to sort them to teams :
game.Players.PlayerAdded:Connect(function(player)
local teamWithLessPlayers = #one_team <= #two_team and one_team or two_team -- if they are equal it will choose team one by default.
table.insert(teamWithLessPlayers, player)
end)
Another thing is that game.Players:GetPlayers() already returns a table, so you can just do local players = game.Players:GetPlayers()
Okay thanks but this function will run one Time and if 8 players are added in the teams the game will start and how will the script know that other 2 players must added into the team before the Game is starting. It counts how much player are in the game but what happens when 7 player are in the game and 1 is loading
local players = game:GetService("Players")
local teams = game:GetService("Teams")
players.PlayerAdded:Connect(function(player)
if #teams.Red:GetPlayers() > #teams.Blue:GetPlayers() then
player.Team = teams.Blue
elseif #teams.Red:GetPlayers() < #teams.Blue:GetPlayers() then
player.Team = teams.Red
end
end)
players.PlayerRemoving:Connect(function(player)
if #teams.Red:GetPlayers() > #teams.Blue:GetPlayers() then
teams.Red:GetPlayers()[1].Team = teams.Blue
elseif #teams.Red:GetPlayers() < #teams.Blue:GetPlayers() then
teams.Blue:GetPlayers()[1].Team = teams.Red
end
end)
Re-assigns player(s) when a player joins/leaves to keep the team sizes balanced. I’ve used two teams “Red” and “Blue” as an example.