Get All Players.Characters

I have encapsulated/abstracted out Enemy logic into a Module Script in the workspace that is being called from a local script from a Model

I have a detect function that I pretty much copied from a tutorial and the example show looping through workspace:GetChildren(). I was hoping to just loop through Player/Characters, but can’t figure out how to do that or my design is just wrong in general.

Here is my current loop that will create a table of “nearby” Models (current hack to filter list down)
I only want to check for the Enemy to detect players.

 for i,v in ipairs(workspace:GetChildren()) do
	if v:IsA("Model") then
		local human = v:FindFirstChild("Humanoid")
		local torso = v:FindFirstChild("HumanoidRootPart")								
                if human and torso and v.Name ~= script.Parent.Name then           
			if (myTorso.Position - torso.Position).magnitude < distSite and human.Health > 0     then
                            table.insert(potentialTargets, torso)
                        end
	         end
 	 end
 end
4 Likes

You will loop through the Players service by GetPlayers then get their character.

for _,player in ipairs(game.Players:GetPlayers()) do
    local character = player.Character
end
9 Likes

A simple modification to @Quwanterz code to account for players that are loading:

for _,player in ipairs(game.Players:GetPlayers()) do
    local character = player.Character or player.CharacterAdded:Wait()
    local humanoid = character:WaitForChild("Humanoid")
	local torso = character:WaitForChild("Torso")
	
	if humanoid and torso then
		if ((myTorso.Position - torso.Position).Magnitude < distSite) and (humanoid.Health > 0) then
			table.insert(potentialTargets, torso)
		end
	end
end

*Edit
@suspectshot108 has an error so i updated mine

I’m just going to format the two answers above to fit your script since they are both valid.

for _,player in pairs(game.Players:GetPlayers() do
	local character = player.Character or player.CharacterAdded:Wait()
	local humanoid = character:WaitForChild("Humanoid")
	local torso = character:WaitForChild("Torso")
	
	if humanoid and torso then
		if (myTorso.Position - torso.Position).Magnitude < distSite and humanoid.Health > 0 then
			table.insert(potentialTargets, torso)
		end
	end
end
2 Likes