How to count the number of players in a team?

Listen, I’ve tried #game.Teams.SampleTeam:GetPlayers(), I’ve seen lots of devforum posts which only give me slight variations of the same concept. I’d usually thing it a logical error with my previous code, but the system tells me its the “#game.Teams.SampleTeam:GetPlayers()” itself. I use it in a script and compare it to a integer value like “1” (if #game.Teams.SampleTeam:GetPlayers() == 1 then) the game gives me the error “attempted to obtain length of an Instance value” no matter how I phrase my code.

Any assistance is greatly appreciated, thank you in advance.

1 Like
local team = teamsService:FindFirstChild(teamName)
local playersInTeam = team:GetPlayers()

-- Count the number of players in the team
local playerCount = #playersInTeam

if playerCount == 1 then
	--script something
end

Try it, trust me

1 Like

I don’t know why adding extra variables to the code fixed it, but it did. is there any difference between “#team:GetPlayers()” (what I did) and using all the variables you did? The results are drastically different, but I don’t understand why my errors happened…
Thank you for the help!

1 Like

To count the number of players in a team, you need to convert the result of game.Teams.SampleTeam:GetPlayers() into a table (which GetPlayers() returns) and then get its length using #

The function # in Lua is used to get the length of a table or a string, but it can’t be directly used on an Instance.

2 Likes

I would try using the other person’s script, but if that doesn’t work you could try one of these

local Count
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
Count = table.maxn(Teams.ExampleTeam:GetPlayers())
if Count == 1 then
	--Do something
end
local Count = 0
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
for _, v: Player in pairs(Teams.ExampleTeam:GetPlayers()) do
	Count += 1
end
if Count == 1 then
	--Do something
end
local Count = 0
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
for _, v: Player in pairs(Players:GetChildren()) do
	if v.Team == Teams.ExampleTeam then
		Count += 1
	end
end
if Count == 1 then
	--Do something
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.