Equally sharing out players on teams

Hey there!

I am trying to create a system for my game where there is a certain amount of teams, and the sever script is supposed to share the players out between these teams (there is 2 teams right now)

I have made a small script in my module to see if this will work but when i test with multiple players, it adds them all to the same team, here is the script:

function module:setTeams()
	for i,v in pairs(game.Players:GetPlayers()) do
		local players = #game.Players:GetPlayers()
		local team1 = game.Teams.Blue
		local team2 = game.Teams.Red
		local playersiterated = 0
		
		for i = 1,players do
			playersiterated+=1
			if #team1:GetPlayers() >= #team2:GetPlayers() then
				v.Team = team1
			else
				v.Team = team2
	
			end
		end
		
		
	end
end

Any help is greatly appreciated!

(I also couldn’t find any videos or DevForum posts related to this topic.)

I think you can simply do this for what you want

local Teams = game:GetService("Teams")
local Players = game:GetService("Players")
function module:setTeams()
	local team1 = Teams.Blue
	local team2 = Teams.Red
	for _,v in pairs(Players:GetPlayers()) do
		if #team1:GetPlayers() >= #team2:GetPlayers() then
			v.Team = team2
		else
			v.Team = team1
		end
	end
end

If team1 has less players it’ll team them to Team1 and if team2 has less players it teams them to Team2

Also, I recommend getting services by GetService so it ensures you get the service rather than indexing

2 Likes

Thank you! This works perfectly, and thanks for the advice!

1 Like

Just a suggestion: you should shuffle the player list first before assigning the teams. It can cause players to stay on the same team until someone joins or leaves the game