PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Create Traps to Set Player Health to 0

Create Traps to Set Player Health to 0

Jun 23 2018, 10:20 AM PST

Problem

You want to create a part that once touched, reduces the player’s health to zero.

Solution

Create a part, and then hook the Touched event and use safe indexing to set the health of the Humanoid to 0.

local part = Instance.new('Part')
part.Anchored = true
part.Parent = workspace
part.Touched:connect(function(hit)
	local hum = hit.Parent:FindFirstChild("Humanoid")
	if hum then
		hum.Health = 0
	end
end)

Hook the Touched event of the parent part of the script and use safe indexing to set the health of the Humanoid to 0.

local part = script.Parent
part.Touched:connect(function(hit)
	if hit.Parent then --common pitfall of kill bricks, without this the script will break when hit by bullets
		local hum = hit.Parent:FindFirstChild("Humanoid")
		if hum then
			hum.Health = 0
		end
	end
end)

Discussion

The Touched event passes the part that touched the object to the callback function. Say the left leg of the player named “Camoy” touched a part we create. The callback function would be called and the hit argument would be set to Workspace.Camoy["Left Leg"]. Now in the line where hum is set, we take the hit variable (the Left Leg in my example) and get its parent. The parent of the Left Leg is the “Camoy” directory. Inside this “Camoy” directory will be all the other parts that make up my character including the Humanoid. We then use safe indexing to index this Humanoid which may or may not be present.

You may be asking yourself, “When would this not be present?”. What happens if another random part touches this part, say Workspace.AwesomePart touches your newly created part. Then hit.Parent would map to Workspace, which might not have a Humanoid in it. The next conditional checks if the Humanoid was actually indexed and then sets its Health to 0. What if hit.Parent doesn’t exist you may ask? The first bit that checks if hit actually has a parent may seem a bit odd at first, but it handles that very situation!

Consider this: a player shoots a gun at the brick, and the bullet hits it, thereby triggering the event. What will happen if the game decides to run the bullet script before your touched handler? The bullet’s script may end up removing the bullet before the call to your script ever gets a chance to call FindFirstChild on the bullet’s parent. Your script would end up failing without the check because it tried to call hit.Parent:FindFirstChild when there is no hit.Parent anymore to call FindFirstChild on!

Tags:
  • traps
  • obstacle
  • obby
  • humanoid