Wait for indefinite number of children?

I have a localscript which is meant to get multiple teleport waypoints across the map in a workspace folder, the issue is the localscript tries checking for these instances before they have even loaded (printing a getchildren of the folder at that point shows it empty)

image
(Waypoint example, spawn is not recognized by the script even with a direct print as it hasn’t loaded yet)

The problem is I can’t use waitforchild as I’d have to manually configure that for each place’s waypoints, I also don’t wanna do a flat task.wait time as that’s unreliable.

In addition to looping through the folder for any spawns that had already existed, the LocalScript could listen for new waypoints to be added to the folder with Instance.ChildAdded.

This would allow for the intended functionality to be assigned to each of the spawns as soon as it’s streamed in to the player, without needing to wait for every spawn to load before calling the function.

Example

local Logic = workspace:WaitForChild("Logic")
local Admin_Teleports = Logic:WaitForChild("Admin_Teleports")

local function waypointFunctionality(item)
    print(item.Name)

    -- Continue
end

for _, item in Admin_Teleports:GetChildren() do
    task.spawn(waypointFunctionality, item)
--[[ Function will be called for the objects that
already exist on the first layer of the folder --]]
end

Admin_Teleports.ChildAdded:Connect(waypointFunctionality)
--[[ Function will be called for any newly added item
that didn't exist when the loop ran --]]
1 Like

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