Looking for Player not Model

I’m making this script, which what it does is looking for the closest humanoid, but the problem is that this script is for a NPC which means if I put a bunch of them they will look for each other (and murder each other) and not the players, so what I need is how can I make that it can look for a player and not the humanoid itself. Pic:Captsdsdsdsdure

Use this to alter your code.

https://developer.roblox.com/api-reference/function/Players/GetPlayerFromCharacter

1 Like

Btw, Instead of having to do dist as 1000000… you could instead do math.huge.

1 Like

You have already selected a solution, however I wanted to point out a few things.

Iterating through the children of workspace is redundant given your desired outcome. You can get an array of players using the :GetPlayers() method on the Players service. I ran a speed test on a small/medium sized game (around 4000 instances) to demonstrate the difference. Iterating through workspace and performing those logic checks took around 100 times longer than the second option.

for _, Player in pairs(game:GetService("Players"):GetPlayers()) do
	-- logic
end

vs

for _, v in pairs(workspace:GetChildren()) do
	
	if v:FindFirstChild("Humanoid") then
		local Player = game:GetService("Players"):GetPlayerFromCharacter(v)
		
		if Player ~= nil then
			-- logic
		end
		
	end
	
end

As you can see, the first option is also far less bloated than the second option. With the first option, you’ll be able to cut out some logic checks since you are already aware the instance is a player. At most, you would need to make sure Player.Character reference is not nil and the Humanoid.Health property is over 0.

On a side note, :children() is deprecated. For future work, you should use :GetChildren() (similar to :GetPlayers(), but returns more than just player instances).

3 Likes