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

Detect Player Health Changes

Detect Player Health Changes

Jun 23 2018, 2:02 AM PST

Problem

You want to print a player’s health if it changes.

Solution

Use the Instance/Changed|Changed event.

game.Players.PlayerAdded:Connect(
	function(pl)
		pl.CharacterAdded:Connect(
			function(char)
				repeat wait() until char:FindFirstChild("Humanoid")
				local hum = char.Humanoid
				hum.Changed:Connect(
					function(p)
						if p == "Health" then
							print(pl.Name .. "'s health is: " .. pl.Health)
						end
					end
				)
			end
		)
	end
)

Discussion

This code will print the player’s health when it changes, for example:

Builderman's health is: 60

First, we use the Players/PlayerAdded|PlayerAdded event and Player/CharacterAdded|CharacterAdded event to get to the character of all the players. Then we wait until we can find the Humanoid in the character. Next we used the Instance/Changed|Changed event and connect it with a callback function. The Instance/Changed|Changed event passes the callback one argument (the property that was changed). We check to see if that property is Humanoid/Health|Health and then print out the health if it is.

Tags:
  • player
  • health
  • event
  • script