I think that would have the same problem: because adding the children is split from the removing children, it’s not guaranteed that the things will happen in exactly the removechildren, addchildren, removechildren, addchildren, etc order. If the functions removechildren, removechildren then addchildren, addchildren, are run, then it’s a problem because we get two sets of added children.
When a function is called in response to an event, its code is run. The responses to events are handled in order, so one changed response is handled, and then the next is handled, and so on.
The problem is that if there is yielding, the entire game doesn’t just stop and wait, so it goes on to handling the next events and comes back to that function call. This means to guarantee the order above, you need to do the order without yielding in between.
This means that yielding at the addchildren level doesn’t work. Instead, you need to break out the yielding used to wait for the “Selection” child, or avoid waiting for that child all together. This makes sure all the children are added without yielding, but also allows the text to be updated.
Here is how that would look:
function removechildren()
for i ,v in pairs(MainFrame.Scroller:GetChildren()) do
if v:IsA("Frame") then
v:Destroy()
end
end
end
function addChildren(Table)
for i, v in pairs(Table) do
if v:IsA("Part") then
local clone = template:Clone()
-- task.spawn is kind of like saying "we need this done, but not *exactly* right now"
task.spawn(function()
-- If we left this wait in sequence, it would be possible for another function call to slip in between while this function call was waiting
clone:WaitForChild("Selection").Text = v.Name
end)
clone.Parent = MainFrame.Scroller
end
end
end
selection.SelectionChanged:Connect(function()
print("EEE")
-- It's very important we do these two right in a line, so they don't get split up
removechildren()
addChildren()
end)
This stuff can take a while to get use to. In languages like JavaScript for web development, a ton of developers go without knowing about this at all since the entire thing largely just runs in sequence.