Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How would I turn this into a function?

This teaming script, is hard to read, could someone explain to me how to turn it into a function, so next time I'll understand, I'm confused of how to make it into a function.

while true do
wait(1)
for i,v in pairs(Game.Players:GetPlayers()) do
team = {"Bright yellow", "Dark stone grey"}
if i ~= #game.Players:GetPlayers() or #game.Players:GetPlayers()%#team ~= 0 then
v.TeamColor = BrickColor.new(team[(i%#team)+1])
else
v.TeamColor = BrickColor.new(team[math.random(#team)])
end
end
wait(3)
for i,v in pairs(Game.Players:GetPlayers()) do
v.TeamColor = BrickColor.new("White")

1 answer

The function you want would probably be to auto assign players to a list of teams.

Its declaration would look like this:

function autoAssignTeams( teams )

Where teams will be a list of Brick Color names.

We can see pretty clearly what to get as the body of the function from what you posted:

for i,v in pairs(Game.Players:GetPlayers()) do
	if i ~= #game.Players:GetPlayers() and #game.Players:GetPlayers() % #teams ~= 0 then
		v.TeamColor = BrickColor.new( teams[(i%#teams)+1] )
	else
		v.TeamColor = BrickColor.new( teams[math.random(#teams)] )
	end
end

So we just wrap this into our functoin:

function autoAssignTeams( teams )
	for i,v in pairs(Game.Players:GetPlayers()) do
		if i ~= #game.Players:GetPlayers() and #game.Players:GetPlayers() % #teams ~= 0 then
			v.TeamColor = BrickColor.new( teams[(i%#teams)+1] )
		else
			v.TeamColor = BrickColor.new( teams[math.random(#teams)] )
		end
	end
end

This is how you would use this function to accomplish the same thing as the snippet you posted in your question:

while true do
	wait(1)
	autoAssignTeams( {"Bright yellow", "Dark stone grey"} )
	wait(3)
	autoAssignTeams( {"White"} )
end

A small note: the implementation is wrong if you want teams to be as even as possible with more than two teams. The i ~= #game.Players:GetPlayers() only applies (in general) as a sufficient check for 2 input teams -- more may be balanced wrong. The solution to this is not very easy, though.

There was also a mistake in the above; it should be using and instead of or

This discussion is preserved as it was. New answers, comments, and votes are closed.