Hello, it is possible to get the parts that is created in workspace by script like Instance.new("Part") but there is more than one part created by the script in ServerScriptService.
So I tried using for IV loops with repeat until loops in it and it didn’t work also I searched any solutions in the devforum and I don’t found any solutions. Can anyone help me?
My solution is to wait until the number of children is reached then continue.
local function WaitForChildren(Instance, Name, Count)
local found = {}
local currentCount = 0
for _, p in pairs(Instance:GetChildren()) do
if p.Name == Name then
table.insert(found,p)
currentCount += 1
if currentCount == Count then
return found
end
end
end
while currentCount ~= Count do
local p = Instance.ChildAdded:Wait()
if p.Name == Name then
table.insert(found,p)
currentCount += 1
end
end
return found
end
Here is an example of how to use the function
WaitForChildren(workspace.Folder, "Part", 5)
This would wait for 5 instances named "Part" under workspace.Folder
The Infinite yield warning is only a warning that appears after 5 seconds of waiting. It will still continue to wait until the child is added and returns it.
WaitForChild only waits for one part with a specific name. It could work if he needs to wait for parts with different names.
i dont think line 9 will work since you’re returning in a loop, try breaking it instead since it will just skip the loop if currentCount is equal to Count
also i recommend settings default to Count in case the parameter wasnt given or want to get all children witht he same name
local function WaitForChildren(Instance: Instance, Name: string, Count: number?)
if Count ~= nil then
Count = math.clamp(Count, 0, math.huge)
if Count >= math.huge then
Count = 0
end
else
Count = 0
end
local found = {}
local currentCount = 0
for _, p in pairs(Instance:GetChildren()) do
if p.Name == Name then
table.insert(found,p)
currentCount += 1
if currentCount >= Count then
break
end
end
end
if Count == 0 then
Count = currentCount
end
while currentCount < Count do
local p = Instance.ChildAdded:Wait()
if p.Name == Name then
table.insert(found,p)
currentCount += 1
end
end
return found
end
It works just fine, I tested it. Returning in a loop is faster than breaking a loop then returning the same value.
I had a different plan in mind that’s why I did not add a default parameter. Getting all children with the same name does not fit the name WaitForChildren, but rather GetChildren with a name parameter.