Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I split up teams in a script?

Asked by 9 years ago

I need help for my game "Strike" and there is a red and blue team and I need to split them up, anyone know how I could do this?

1 answer

Log in to vote
2
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
9 years ago

Well, if you want them to be even, you can enable the AutoAssignable property of Team and Roblox will automatically make them even.

If you need to do this through a script, then you must use a for loop to loop through all the players and change their TeamColor property.

local players = game.Players:GetPlayers()
for i = 1, #players do --Using a numerical for loop so we get numerical iteration.
    local player = players[i]
    player.TeamColor = BrickColor.new("Really red") --Change the teamcolor to red
end

Obviously, this will simply set everyone's team color to the same team; Really red. To set half the players to one team and half to the other, we have two options.

The first is to simply make it so that all the even numbers are set to one team, and all the odd numbers are set to the other team. Since the modulus operator (%) returns the remainder after dividing the given numbers, if we do 4 % 2 it will equal 0, since 4 is even. But if we do 3 % 2 it will equal 1, since 3 is odd.

local players = game.Players:GetPlayers()
for i = 1, #players do 
    local player = players[i]
    if i % 2 == 0 then
        player.TeamColor = BrickColor.new("Really red")
    else
        player.TeamColor = BrickColor.new("Really blue")
    end
end

The other way of doing it is to take half the players (#players / 2) and put them on a single team, and the other half on the other team.

local players = game.Players:GetPlayers()
for i = 1, #players do 
    local player = players[i]
    if i >= #players / 2 then
        player.TeamColor = BrickColor.new("Really red")
    else
        player.TeamColor = BrickColor.new("Really blue")
    end
end

If the number of players in the server is not even, #players / 2 will return a decimal. I do not think this will be a problem, as long as we're doing greater than or equal to (>=). However, if this is glitchy for you you may have to use math.ceil(), which just rounds the number up to the nearest integer.

0
And where and how can I get the players in the teams? User#29793 0 — 4y
Ad

Answer this question