So I made this script so that my game doesn’t lag but it still doesn’t work it is suppose keep 25 CocoaBeans and delete the rest but just in this folder which is called CocoaBeans. I tried putting it in a loop but it just did it once straight away as soon as I join so therefor got rid of nothing. Please help me fix this script or tell me another way of how I can do it.
local children = workspace.Trees.CocoaBeans:GetChildren()
local count = #children
if count == 25 then
workspace.Trees.CocoaBeans.Cocoa:Remove()
print("removed a coco bean")
end
change if count == 25 then
to if count > 25 then
edit: also put the script in a loop
still doesnt work
while true do
local children = workspace.Trees.CocoaBeans:GetChildren()
local count = #children
if count > 2 then
workspace.Trees.CocoaBeans.Cocoa:Remove()
print("removed a coco bean")
end
end
while true do
local children = workspace.Trees.CocoaBeans:GetChildren()
local count = #children
if count > 25 then
workspace.Trees.CocoaBeans.Cocoa:Remove()
print("removed a coco bean")
end
wait()
end
you need a wait()
3 Likes
I know a solution has been given but I’d like to give my two cents
There’s an event that handles exactly what you need without a loop, ChildAdded
, which listens for when a child is added to an Instance, in your case a folder. You can make it so when the event is fired, it checks the amount of getchildren in the folder and the destroy the newly added thing if it would go over the limit
Something like this
local cocoaTrees = workspace.Trees.CocoaBeans
local limit = 25
local function destroyIfOverLimit(child)
if #cocoaTrees:GetChildren() <= limit then
return
end
child:Destroy()
print("Destroyed bean")
end
cocoaTrees.ChildAdded:Connect(destroyIfOverLimit)
for _, part in ipairs(cocoaTrees:GetChildren()) do
destroyIfOverLimit(part)
end
I included the
for _, part in ipairs(cocoaTrees:GetChildren()) do
destroyIfOverLimit(part)
end
In the event there’s already more than needed instances in the folder before the event is made, it may not need be that needed so you can just remove it.
Also, Remove
is deprecated and Destroy
should be used instead
2 Likes