WaitForChild() or .ChildAdded?

I’m working on a tycoon framework. More specifically, the function that allows buttons that depend on prior purchases to appear only once those purchases have been made. Essentially, I just need to wait until new child is added to the purchases folder and make the button appear. However, I thought of two ways of doing this and wondered which is better practice.

The first is using WaitForChild(), listening for each dependency.

for i,button in pairs(Tycoon:WaitForChild("Buttons"):GetChildren()) do
	spawn(function()
		if button:FindFirstChild("Config") then
			coroutine.resume(coroutine.create(function()
				for i,dep in pairs(Config.Dependency:GetChildren()) do
					Tycoon.Purchased:WaitForChild(dep.Value)
				end
				--spawn in button
			end))
		end
	end)
end

The second is using .ChildAdded, and checking if the purchase is the same as the dependency.

for i,button in pairs(Tycoon:WaitForChild("Buttons"):GetChildren()) do
	spawn(function()
		if button:FindFirstChild("Config") then
			for i,dep in pairs(Config.Dependency:GetChildren()) do
				Tycoon.Purchased.ChildAdded:Connect(function(purchase)
					if purchase.Name == dep.Value then
						--spawn in button
					end
				end)
			end
		end
	end)
end

I couldn’t find any topics comparing the two options and I wanted to know which, if either, is better practice. Or is there a better way than either of these that I’m not thinking of? Thanks.

Well, they both to something else, WaitForChild waits for a child and searchs for it you can also give a number with it to wait. If not seen it will stop waiting. ChildAdded is more when a child gets added to something, not if the child already exits inside the model. This is WaitForChild is mostly used on the client side because the player still needs to load stuff in. From what I know/think.

2 Likes

In this case, since the object isn’t there until purchased, WaitForChild() yields until the object is purchased, which seems the same as .ChildAdded. When I run both of the scripts, they work identically, so which do you think would be more performant?

WaitForChild would create a decent amount of connections. In plan of optimization ChildAdded will be way better.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.