Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do you count the number of entities inside of a folder?

Asked by
yodafu 20
5 years ago
Edited 5 years ago

I've been trying to find the number of models inside of a folder named Ingame. These models will be players who are currently playing a level, and once the number of players in the Ingame folder reaches 1, a GUI will appear naming them as the winner. Here is my code so far...

local ingame = workspace.Ingame:GetChildren()
    if vals.Winner.Value ~= "" then
        s.Value = vals.Winner.Value.. " has won!"
        vals.Winner.Value = ""
    elseif ingame < 2 then
        vals.Winner.Value = ingame:GetFirstChild()
        s.Value = vals.Winner.Value.. " has won!"
        vals.Winner.Value = ""
        else
        s.Value = "No one has won!"

I have tried creating another variable that turns ingame into a number, by doing local ingamenum = ingame.tonumber() but this didn't seem to work, and I can't quite get my head around how I would do this otherwise. Any help is appreciated!

0
use key value pairs RetroGalacticGamer 331 — 5y
0
#Folder:GetChildren() works for getting the number of children a folder has theking48989987 2147 — 5y
0
@theking48989987 see my answer TerrodactyI 173 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

GetChildren() returns a table, to get the number of things inside that table use #, the table length operator. Additionally, GetFirstChild doesn't exist (around line 6), use [1] to get the first entry. Also, GetChildren doesn't return a table of strings, so you need to use .Name to get the name of the model/player Instance. Also, in the second block, vals.Winner.Value is already blank since the first condition wasn't met. Here:

local ingame = workspace.Ingame:GetChildren()

if vals.Winner.Value ~= "" then
    s.Value = vals.Winner.Value .. " has won!"
    vals.Winner.Value = ""
elseif #ingame == 1 then 
    s.Value = ingame[1].Name .. " has won!"
else
    s.Value = "No one has won!"
end

This can be further simplified to:

local ingame = workspace.Ingame:GetChildren()
local winner = 'No one'

if vals.Winner.Value ~= '' then
    winner = vals.Winner.Value
elseif #ingame == 1 then 
    winner = ingame[1].Name
end

vals.Winner.Value = ''
s.Value = winner .. ' has won!'

Remember to upvote and accept if this answer helped!

Ad

Answer this question