How to "flip" children?

Hey!

How do you flip the order of :GetChildren()? GetChildren always grabs from the new children, then moves towards the old, is there way to flip this?

Why do you need to do this? Is there a different way you could go about this? Typically you don’t want to rely on the order of children.

But if you must, you could try two separate things:

  1. Get children, unparent them all, then reparent them in reverse.
  2. Get children. Clone them. Parent them in reverse order. Delete the originals.
1 Like

In my game, things are spawning in, and I want to delete the old things instead of deleting the new things.

if #parts:GetChildren() > player.Parts.Value then
    local c = parts:GetChildren() 
	local amountToGetRidOf = player.Parts.Value - #c
	for i = math.abs(amountToGetRidOf), 1, -1 do
		c[i]:Destroy()
	end
end

Would you recommend going another way about this?

1 Like

You could add a delay function in for each object created that removes it after a certain period of time.

You shouldn’t really assume :GetChildren() returns children in any order. If you want to order children, I’d recommend adding an “IntValue” and setting it to a number, and then do this

local unsortedChildren = self:GetChildren()
local sortIndex = {}
for _, child in pairs(unsortedChildren) do
    sortIndex[child] = child:FindFirstChild("SortedIndex") and child.SortedIndex.Value or 1
end

table.sort(unsortedChildren, function(a, b)
     return sortIndex[a] < sortIndex[b]
end)
5 Likes

Yes, there is actually a function designed for this, if you simply want to delete an object after a given period of time. The Debris service has a function, Debris:AddItem() that will delete an object after a passed amount of time.

Otherwise, if you purely want to delete the oldest object then you could just make a table, and insert the newest object at the end of that table. When you want to delete an object, just use table.remove() to delete the first entry in the table. This method may not be the fastest, but should work very well in most situations and is the simplest solution that I could think of.

2 Likes

I think something like that may be the best solution for me. I’d use debris if I knew how long objects would be spawned for, but I do not.

What’s the criteria for parts to be removed? Maybe there’s a better way of recording it.