Can this be made more efficient?

Hello! This is my first post in Code Review, before I’ve posted in scripting support but this is the first time I’ve had working code that I want to improve!

Anyway, I was trying to make a simple game mechanic to make a Mario-like game. I created a script that detected if a player was touching an enemy. If the player touched the enemy’s head with their feet, the enemy would die. If the player touched the enemy in any other way, they would die. This is my code.

local enemy = script.Parent
local head = enemy.Head
local torso = enemy.Torso
local leftarm = enemy["Left Arm"]
local rightarm = enemy["Right Arm"]
local leftleg = enemy["Left Leg"]
local rightleg = enemy["Right Leg"]

head.Touched:Connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	if hum then
		if hit.Name == "Left Leg" or hit.Name == "Left Leg" then
			enemy:Destroy()
		end
	end
end)

torso.Touched:Connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	if hum then
		hum.Health = 0
	end
end)

leftarm.Touched:Connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	if hum then
		hum.Health = 0
	end
end)

rightarm.Touched:Connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	if hum then
		hum.Health = 0
	end
end)
leftleg.Touched:Connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	if hum then
		hum.Health = 0
	end
end)
rightleg.Touched:Connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	if hum then
		hum.Health = 0
	end
end)

This was pretty annoying to write out, so I was wondering if there was any way to combine some of these, like an “or” gate, making it like “if torso or leg or arm or blah blah blah touches blah then do blah” instead of writing out every individual thing. But I don’t know how to do that.

Thanks!

This whole code here is very inefficient. I would recommend you to make a table of all these instances, then loop through them and connect them into a touched event.

The second thing is instead of checking if the hit part’s Parent has a humanoid child, use game.Players:GetPlayerFromCharacter(hit.Parent). This will make sure if the hit.Parent is a real player. Overall, good job on the script.

3 Likes