Character detection on input

In short I have a LocalScript that on MouseButton1 checks if there are any players in a hitbox (a part).

I’ve spent quite some time trying to get this code to this point and for not leaving anything out I ask you if anything can be improved.

Here’s the current state:

local userInput = game:GetService('UserInputService')

local character = script.Parent

local combatHitbox = character:WaitForChild('CombatResources'):WaitForChild('Hitbox')

userInput.InputBegan:Connect(function(inputObject, gameProcessedEvent)
	if not gameProcessedEvent and inputObject.UserInputType == Enum.UserInputType.MouseButton1 then
		local charactersInHitbox = {}
		local partsInHitbox = workspace:GetPartsInPart(combatHitbox)
		for _, part in ipairs(partsInHitbox) do
			if part.Parent:FindFirstChild('Humanoid') and part.Parent.Name ~= character.Name and character:FindFirstChild('Humanoid').Health > 0 then
				local characterInHitbox = part.Parent
				if not table.find(charactersInHitbox, characterInHitbox) then
					table.insert(charactersInHitbox, characterInHitbox)
				end
			end
		end
		print(charactersInHitbox)
	end
end)

It looks pretty good but I have some suggestions:

if part.Parent:FindFirstChild('Humanoid') and part.Parent.Name ~= character.Name and character:FindFirstChild('Humanoid').Health > 0 then
	local characterInHitbox = part.Parent
	if not table.find(charactersInHitbox, characterInHitbox) then
		table.insert(charactersInHitbox, characterInHitbox)
	end
end

could be

local characterInHitbox = part.Parent
if characterInHitbox ~= character and characterInHitbox ~= workspace then
	local humanoid = characterInHitbox:FindFirstChildWhichIsA('Humanoid')
	if humanoid and humanoid.Health > 0 then
		if not table.find(charactersInHitbox, characterInHitbox) then
			table.insert(charactersInHitbox, characterInHitbox)
		end
	end
end
1 Like