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.
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
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!
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.
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