Hi, my original script is a bit longer, but I’m trying to make a system where it counts the number of objects based on a name, i.e number of cheese and number of bacon.
However, there’s more than just those 2 objects and I can’t continuously make if then statements.
I’m also unable to make my script be able to detect if there is a loss of object too, so can you help me in this?
local FOLDER = workspace.Folder
local CHEESE = 0
for i,v in pairs(FOLDER:GetChildren()) do
if v.Name == "Cheese" then
CHEESE = CHEESE + 1
end
end
print(CHEESE)
You could keep a dictionary that has a list of objects and a set value to them:
local FOLDER = workspace.Folder
local OBJECTS = {
['Cheese'] = 0
}
for i,v in ipairs(FOLDER:GetChildren()) do
if OBJECTS[v.Name] then -- checks if the OBJECTS table has the object's name in it
OBJECTS[v.Name] += 1 -- adds one
end
end
print(OBJECT.Cheese)
For your script to detect an object’s removal, you can do something like this:
FOLDER.DescendantRemoving:Connect(function(desc)
if OBJECTS[desc.Name] then
OBJECTS[desc.Name] -= 1 -- removes 1
end
end)
-- Your folder
local FOLDER = workspace.Folder
-- Need this for storing our numbers
local foodDictionary = {
["CHEESE"] = 0,
["PIZZA"] = 0,
["ICECREAM"] = 0
}
for _, food in ipairs(FOLDER:GetChildren()) do
-- Checking if our food is even valid
if foodDictionary[food.Name] then
foodDictionary[food.Name] += 1
end
end
print(foodDictionary.CHEESE) -- Returns amount of cheese
Every time you want to add a new food, add it to the dictionary!