Effectively created a "WaitForChildWhichIsA" function

--The Name of this ModuleScript is "UtilityModule"
--This ModuleScript is found inside ServerScriptService

local UtilityModule = {}

function UtilityModule.WaitForChildWhichIsA(parent, className)
    assert(typeof(parent) == "Instance", "Parent must be an Instance")
    assert(type(className) == "string", "Class name must be a string")

    local child = parent:FindFirstChildWhichIsA(className)
    while not child or not child:IsA(className) do
        child = parent.ChildAdded:Wait()
    end
    return child
end

return UtilityModule

Script that uses the function:

local UtilityModule = require(game.ServerScriptService.UtilityModule)

game.Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)

        local Humanoid = UtilityModule.WaitForChildWhichIsA(character, "Humanoid")
		local HumanoidRootPart = character:WaitForChild("HumanoidRootPart")
		
		print(Humanoid)
		print(HumanoidRootPart)
		
        local equippedTool = nil

        while true do
            local newEquippedTool = UtilityModule.WaitForChildWhichIsA(character, "Tool")
            
            if equippedTool ~= newEquippedTool then
                equippedTool = newEquippedTool
                print("Equipped Tool:", equippedTool)
            end
            
            wait()
        end
    end)
end)

In this example, we are using the function twice to show that it can be used more than once in the same function. I’m not sure if roblox has yet implemented a WaitForChildWhichIsA quick function but I hope this helps someone

1 Like

Asinine example showcasing an asinine function.

There’s zero point in wrapping Instance.ChildAdded:Wait() in a while loop, wrapping that in a function, then calling that from yet another while loop.

The following would completely undermine any and all merit your “utility” function could ever possess:

local equipped: Tool? = nil

Character.ChildAdded:Connect(function(child: Instance)
    if child:IsA("Tool") then
        equipped = child
        print(`Equipped tool: {child}`)
    end
end)

The function replicates the behavior of Instance:WaitForChild, which halts the thread. If you were to use your approach, you would still need to wait for equipped to be assigned something before proceeding

2 Likes

Neat function! Also you may be interested in reading why roblox never added this themselves

4 Likes