Detect entities around character

How do I get all humanoids around the player character and return them into an array?
Preferably an array and every time a humanoid enters within a 60 stud range of the player character this humanoid gets added into the array as an instance value.

Is your system going to work for all entities with a Humanoid, like NPCs and players, or just players?

Here I’ve created a function that returns a table with only NPCs in a 60 stud radius.

module.returnTorsosInArray = function(pos, part, user, dist)

	local list = game.Workspace:children()
	local array = {}
	if dist == nil then
		dist = 60
	end
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and game.Players:GetPlayerFromCharacter(temp2) == nil then
			temp = temp2:findFirstChild("HumanoidRootPart")
			human = temp2:findFirstChild("Humanoid")
			dist = (temp.Position - pos).magnitude
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) and dist <= 60 then
				table.insert(array, #array+1, temp)
			end
		end
	end
	return array
	
end

I need this array constantly updating… but I don’t think It’d be a good idea to run it in a while loop, would it?

One solution, if you are working with both NPCs and players, is to define a radius around the player’s character. Then run a RunService.Heartbeat event and loop through a table of all entities with a Humanoid in them and check if (Character.RootPart.Position - Entity.Character.RootPart.Position).Magnitude is less than or equal to the radius, if so do what you wanted to.

To improve this even further you could implement a sort of chunk system so instead if looping through all entities you would only loop through the entities in the chunk area.

1 Like