Checking for Humanoids near a player

Hey! I’m trying to make a wand be used as a melee weapon or ranged weapon depending on how close you are to an enemy.

My problem is that the script checks for humanoids, but only focuses on one not regarding any other humanoids in the area. If anyone could help me with this I would be very thankful.

Here is my issue

Code:

	for _, humanoids in pairs(game.Workspace:GetDescendants()) do
		if humanoids:IsA("Humanoid") and humanoids ~= plr.Character:FindFirstChild("Humanoid") then
			local target = humanoids:FindFirstAncestorOfClass("Model")
			if target and target ~= plr.Character then
				if target.PrimaryPart or target:FindFirstChild("Humanoid") then
					local distance = (plr.Character.HumanoidRootPart.Position - target:FindFirstChild("HumanoidRootPart").Position).magnitude
					if distance <= 10 then
						return "MeleeRange"
					else
						return "CastRange"
					end
				end
			end
		end
	end
1 Like

The problem is you’re returning after reaching the first humanoid which stops the for loop. But removing the return would mean the function that does this code wont have a value anymore. So instead of printing out the value of the function, you could replace the return with a print.

2 Likes

You should probably use an array to build a list of humanoids and add each ‘match’ to the list, then when you’re done return that list.

4 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.