do how do I make a variable that represents everything thats named food.
and how do I put it in touched function.
do how do I make a variable that represents everything thats named food.
and how do I put it in touched function.
function SearchForObjects(parent, name, recursive, listenForAdded)
local found = {}
local temp = {}
if recursive then
temp = parent:GetDescendants()
else
temp = parent:GetChildren()
end
local function addObject(object)
if object.Name == name then
table.insert(found, object)
end
end
for _, object in pairs(temp) do
addObject(object)
end
if listenForAdded then
if recursive then
parent.DescendantAdded:Connect(addObject)
else
parent.ChildAdded:Connect(addObject)
end
end
return found
end
local Part = script.Parent
--searching for "food", inside workspace, recursively(for example it may be inside Baseplate), and listening for new "food" being added
local ObjectsNamedFood = SearchForObjects(workspace, "food", true, true)
Part.Touched:Connect(function()
print(ObjectsNamedFood)
end)
local part = script.Parent
part.Touched:Connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") then
local foods = {}
for _, instance in ipairs(workspace:GetDescendants()) do
if instance.Name:lower() == "food" then
table.insert(foods, instance)
end
end
print(#foods.." is the current number of foods!")
end
end)