So I'm trying to make a script that counts the amount of parts in the game.
I made this simple script
local parts = game.Workspace:GetChildren() print(parts)
Since I'm new to using Tables and stuff, the output came out with this:
table: 17CC8988
Is there any way to get the number of how many of them is in? I'm planning on making a Gui that counts how many are left.
Well, to get the number of elements in a table, you must you #Table
, which returns highest numerical index in a table.
Also, to get only parts, you must do instance:isA'BasePart', with BasePart meaning all part classes.
Example script:
local Parts={};--// Table to contain parts. for _,Object in next,workspace:children()do if(Object:isA'BasePart')then--// Gets all part instances. table.insert(Parts,Object);--// Puts the parts in a part table. end; end; print(string.format('Number of parts in the Workspace: %d',#Parts));--// Prints the amount of parts.
If you wanted to get every part in the workspace, even parts that are in models, you would have to use recursion.
Example #2:
local Parts do local Recursion;Recursion=function(Object) local Children={}; for _,Child in next,Object:children()do if(Child:isA'BasePart')then table.insert(Children,Child); end; for _,Descendant in next,Recursion(Child)do--// Gets all the descendants. table.insert(Children,Descendant); end; end; return(Children); end; Parts=Recursion(workspace); end; print(string.format('Number of parts in the Workspace: %d',#Parts));--// Prints the amount of parts.
If you want to make a list of all the parts that are named a certain string, just have a table for containing them.
Example #3:
local Parts={}; do local Recursion;Recursion=function(Object) local Children={}; for _,Child in next,Object:children()do if(Child:isA'BasePart')then table.insert(Children,Child); end; for _,Descendant in next,Recursion(Child)do--// Gets all the descendants. table.insert(Children,Descendant); end; end; return(Children); end; for _,Part in next,Recursion(workspace)do Parts[Part.Name]=Parts[Part.Name]or {}; table.insert(Parts[Part.Name],Part); end; end; for PartName,arrayOfParts in next,Parts do print(string.format('Number of parts named %s in the Workspace: %d',PartName,#arrayOfParts)); end;
local parts = game.Workspace:GetChildren() for i=1, #parts do if (parts[i].className == "Part") then print(#parts) end end
Use the number sign behind the parts
when you print. And also do
for i=1, #parts do if (parts[i].className == "Part") then
To check if the thing in Workspace is a part.