Randomise Team Script only teams 1 Players

image
As you can see when I am testing in Studio, my team randomiser script only teams one player for some reason.

Script:

local teams = {'Really red', 'Really blue' , 'New Yeller' , 'Institutional white'}
local team = {{''},{''},{''},{''}} 
local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(plr) 
	local plrs = Players:GetChildren()
	if #team[1] == #team[2] then
		local choosed = math.random(1,2)
		table.insert(team, choosed, plr)
		plr.TeamColor = BrickColor.new(teams[choosed])
	elseif #team[1] < #team[2] then
		table.insert(team, 1, plr)
		plr.TeamColor = BrickColor.new(teams[1])
	elseif #team[1] > #team[2] then
		table.insert(team, 2, plr)
		plr.TeamColor = BrickColor.new(teams[2])
	end
end)

Players.PlayerRemoving:Connect(function(plr)
	if plr.TeamColor == 'Really red' then
		for i = 2, #team[1] do
			if team[1][i] == plr.Name then
				table.remove(team, 1, i)
				break
			end
		end
	elseif plr.TeamColor == 'Really blue' then
		for i = 2, #team[2] do
			if team[2][i] == plr.Name then
				table.remove(team, 2, i)
				break
			end
		end
		
	elseif plr.TeamColor == 'New Yeller' then
		for i = 3, #team[3] do
			if team[3][i] == plr.Name then
				table.remove(team, 3, i)
				break
			end
		end

	elseif plr.TeamColor == 'Institutional white' then
		for i = 4, #team[4] do
			if team[4][i] == plr.Name then
				table.remove(team,4, i)
				break
			end
		end
	end
	
end)

Any help would be appreciated, thanks!

Your issue is, you are inserting a player into the wrong table! Currently, you are using;

local choosed = math.random(1,2)
table.insert(team, choosed, plr)

Here is what your table would look like (‘4a’ would be a player object)
fd51a32ce6bdfda3da7ba8b0624fd2ee

However! You are inserting a new value into ‘team’ table instead of the specific team table (i.e team[1], team[2]).

I believe your solution is,

local choosed = math.random(1,2)
table.insert(team[choosed], plr)

In this case you do not need to set an index of where the player needs to go; however, you need to identify which table you are wanting to insert the player into!

Please let me know if this helped you!

hm, thanks. but it only inserts two players into a team now, even when i do math.random(1,4)

Actually, forget that script, I made a new one that teams you to a random team, but this does not balance and I don’t know why.

local Teams = game:GetService("Teams")
local Players = game:GetService("Players")
local Children = Teams:GetChildren()


Players.PlayerAdded:Connect(function(player)
	for _, player in pairs(Players:GetPlayers()) do
		if player.Team == Teams.Lobby then
			local randomTeam = Children[math.random(1, #Children)] 
			player.Team = randomTeam
			
			print(player.Name .. "'s team is now " .. randomTeam.Name)
		end
	end
end)