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

How to remove a team if no ones in it then add it back again?

So basically I came across something that I really needed. It was, when no one is in a team the team is removed from the leader board and it gets put in a file in teams. Then when a player enters that team it re appears. Then that process should loop. After using that script I tried it in everything. A script in SSS, workspace, startergui in a local script, everywhere. but it never worked

So for the team removal

local Teams = game:GetService("Teams")
		
for _, team in pairs(game.Teams:GetDescendants()) do
	if team:IsA("Team")then
		team.PlayerRemoved:connect(function(player)
   	 		local players = team:GetPlayers()
   
			if #players <= 0 then
				team.Parent = game.Teams.NotInUse
			end
		end)	
	end	
end

And for the Adding it back

    local Team = "NameOfTeam"
    local function GetTeamByNameInUnused(name)
    			if game.Teams.NotInUse:FindFirstChild(name) then return game.Teams.NotInUse[name] end
    				for _, team in pairs(game.Teams.NotInUse:GetChildren()) do
    					if team.Name:sub(1, name:len()):lower() == name:lower() then
    					return team
    				end
    			end
    		end		

    		local team = GetTeamByNameInUnused(Team)
    		
    		if team then
    			team.Parent = game.Teams
    			Player.Team = team
    		end

Thank you.

1 answer

Team.PlayerRemoved will still have the player on the team for one frame, and this is a known bug. This is the one frame that the script immediately runs in, so it will see that the player is still there and it will not do anything.

As an alternative, Players.PlayerRemoving should be viable for this type of situation. It does fire right before the player leaves, but then you can poll for when they actually leave the game and check if their Team has no remaining players. If this doesn't suit you, you could literally poll for the player to not exist under Players:

repeat wait() until not game.Players:FindFirstChild(player.Name)

But this is just me, and something that isn't this may work as long as it relates to checking if the player has left the server.

EDIT

I did also come up with just using wait() before actually doing anything inside the function. Recall that Team.PlayerRemoved fires one frame before the player leaves. The wait() function yields for 2 frames (1/30th of a second), so it's perfect for this.

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