Getting all humanoids

How do I get all players and anything with a humanoid without looping through every part in the workspace?

My responses may be a bit slow, sorry for that.

There were very good solutions.

1 Like

I don’t think there is a way without looping through a large amount of parts. You can however minimize the amount searched, for example by only searching for humanoids under models.

Say you loop through all children of workspace, then loop through each child of those children IF the child is a model/folder. That would reduce the amount of parts checked.

1 Like

Just use for loop.

for _, player in pairs(game.Players:GetPlayers()) do
	--Get the character then get the humanoid
end

I would do that but I also want other humanoids

Then there are no choice but to loop the entire workspace. What you could do is save those humanoid in a table, let’s say for example if a player joins the game then add them to the table along with the parts that has the instance “humanoid” though this will change once the humanoid died, so maybe also create a function if you’re adding new humanoid add them again in the table, also remove the once that don’t exist. If all you’re doing is on the server side.

2 Likes

Wouldn’t that be a worse result as I still have to loop through all children and also check again with the models?

You have to loop through each part inside the workspace, but if you got a lot of parts, you can just put them all in a folder or a single model.

1 Like
local function GetHumanoid(Hum,Player)
    local tab = {}
    if tab[Hum] == nil then
       tab[Hum] = Player.Name
    end
    return tab
end

game.Players.PlayerAdded:Connect(function(Player)
    Player.CharacterAdded:Connect(function(Char)
        GetHumanoid(Char:WaitForChild("Humanoid"),Player)
    end)
end)

for _,Player in pairs(game.Players:GetPlayers()) do
    local Char = game.Workspace:FindFirstChild(Player.Name)
    local hum = Char:WaitForChild("Humanoid")
    GetHumanoid(hum,Player)
end

You can do something with recursion

local tab = {}
local function FindAllHumanoids(Parent : Instance)
	if Parent:FindFirstChild("Humanoid") then
		table.insert(tab,Parent:FindFirstChild("Humanoid"))
	else
		for _,v in Parent:GetChildren() if v:IsA("Model") then FindAllHumanoids(v) end end
	end
end

(my comment broke lol?)
Or create folder which contains all humanoids

1 Like

Nah you only have to do this once, at the start of the game, or you could manually add them on a table, Im talking about ModuleScript.

1 Like

Almost like this but I would prefer

for i, v in pairs(game.WorkSpace:GetDescendants()) do
if v.Name == "Humanoid" then
local Humanoid = v	
-- any and all Humanoids within Workspace, players, NPC, etc.
end
end