I need help with a very basic problem related to assigning teams

So, I tried to make a script that will make a player king whenever he joins a server and no one else is king, for some reason it’s not working. No output response by the way.


game.Players.PlayerAdded:connect(function(player)

	for i,v in pairs(game.Players:GetChildren()) do
			
		if not v.Team == game.Teams.King then

		local ap = game.Players[player.Name]
		ap.Team = game.Teams.King

		end
	end
end)

You can resolve this really easily by using the appropriate methods of teams and reading up on some API articles. The loop here is completely unnecessary.

Other nitpicks for your current code: GetPlayers is the canonical way to fetch the array of players, not GetChildren, so try conditioning yourself to use the former in the future. You also don’t need to reindex the player when it’s passed as an argument to PlayerAdded.

You resolve this problem by getting rid of the loop and instead checking for the number of players on the King team. Teams also have a GetPlayers method.

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

local KING_TEAM = Teams.King

Players.PlayerAdded:Connect(function (Player)
    if #KING_TEAM:GetPlayers() == 0 then
        Player.Team = KING_TEAM
    end
end)
1 Like

Why not do this?

local checkKing = function()
    if #KingTeam:GetPlayers() == 0 then
        local candidates = Players:GetPlayers()
        candidates[math.random(#candidates)].Team = KingTeam
    end
end

This isn’t exactly what you wanted I think but it will pick a random player to be king if there is not one. You can attach this to both PlayerAdded and PlayerRemoving.

Oh thanks, this is my first time messing around with teams, pretty nice to learn that you could check how many players are on a Team. Big thanks!

Thanks for the script but the only two ways to get King in this game are by joining the server first or by killing the king, so that wouldn’t work well.

I see but then what if nobody else joins? Will there just be no king?

Yeah, I see what you mean now, It’s kinda late night here so my brain is crazy, I will use your script in case the King leaves and he didn’t set any Heirs.

1 Like