Combine the recursive functionality of FindFirstChild with WaitForChild and you have something useful and wonderful.
WaitForC is pretty much a FFC check, then a connection to ChildAdded, it would be simple to make your own, that connected to DescendantAdded instead
local function waitForChild(parent, childName, isRecursive)
local eventSignal
local function fetch(child)
if childName == child.Name then
eventSignal:disconnect()
return child
end
end
if isRecursive then
eventSignal = parent.DescendantAdded:connect(fetch)
else
eventSignal = parent.ChildAdded:connect(fetch)
end
end
something something didn’t test it
[quote] local function waitForChild(parent, childName, isRecursive)
local eventSignal
local function fetch(child)
if childName == child.Name then
eventSignal:disconnect()
return child
end
end
if isRecursive then
eventSignal = parent.DescendantAdded:connect(fetch)
else
eventSignal = parent.ChildAdded:connect(fetch)
end
end
something something didn’t test it [/quote]
What about just this?:
What about not having the function call an expensive engine-side method every frame?
local function waitForDescendant(instance, name)
local descendant = instance:FindFirstChild(name, true)
if not descendant then
repeat
descendant = instance.DescendantAdded:wait()
until descendant.Name == name
end
return descendant
end
What about not having the function call an expensive engine-side method every frame?[/quote]
I’m sorry, ‘expensive engine-side method’? Yielding a coroutine and resuming it isn’t that expensive from what I remember.
That’s the “every frame” part, not the “expensive method” part. Hint: wait isn’t a method
Calling engine-side methods like FindFirstChild from Lua is expensive. That code calls that method every frame, more than 30 times per second! Osyris’ code uses events, which is much better.
Osyris’ code doesn’t return anything. The return statement is inside of a listener, not in the function’s body.
This should be built into ROBLOX.
Since this thread was bumped…
Yeah, I wrote that very quickly without testing it.
This version should work fine:
local function waitForChild(parent, childName, isRecursive)
local child = parent:FindFirstChild(childName, isRecursive)
while true do
if child and child.Name == childName then
return child
end
if isRecursive then
child = parent.DescendantAdded:wait()
else
child = parent.ChildAdded:wait()
end
end
end