I’m working on an FPS game and I’m trying to create a “Squads Mode” where there are four separate teams and they all battle. However, I’ve never worked with teams before and I’m a pretty new developer so I’m not sure how I could evenly assign the players to teams. I tried to use the AutoAssignable property but I quickly realized that it will only auto assign players that are newly added to the server and it won’t work if the players were set to neutral before the other teams were added.
Please search for your topic before posting. A very similar topic already exists. Also, please attempt to script your own solution before posting here.
Here’s a very concise, efficient method of distributing players among teams:
local plrs = game:GetService("Players")
local teams = game:GetService("Teams"):GetTeams()
for i, plr in pairs(plrs:GetPlayers()) do
plr.Team = teams[((i-1)%#teams)+1]
end
The above method uses the index returned by the iterator function to determine the player’s team based on the amount of teams.
If you have 20 players, i
will be a number from 1-20, unique for each player. We use the modulo operation (%) to find the remainder of i-1 (we use i-1 so we start at 0 instead of 1) and the number of teams, then we add one (4%4 == 0, we don’t want 0 since lua arrays start with 1).
6 Likes