Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Reset dummy's health to 100 when it reaches 50 how to fix ?

Guys i've been trying to do this simple script but i don't get why it doesn't work

local hum = script.Parent:FindFirstChild("Humanoid")

while true do
	wait()
	print(hum.Health)
end

if hum.Health == 50 then
	hum.Health = 100
end

i added a server script into the dummy but why it doesnt work the dummy just dies

2 answers

The code isn't actually getting to the if statement, it is just repeating the while true do statement

For this type of script I would use the changed function

fix:

local hum = script.Parent:FindFirstChild("Humanoid")


hum.Changed:connect(function()
if hum.Health <= 50 then
    hum.Health = 100
end
end

6 comments

0

I was gonna say that but yeah, guy who wrote this question kinda inexperienced :/

0

that's ok, he wants to learn

0

ye i forgot about the infinite loop but why it doesnt work whitout the .Changed why i cant just type the if without the function

0

The if function will run once, checking if the humanoid's health is lower than 50 only when the script runs and never again, so it wont be checking if the humanoid's health is less than 50 later on, when it happens. By using the .Changed, the if statement will run when the humanoid's health changes in any way, such as when it goes below 50.

0

You could also use spawn(function() so the code wouldn't yield at the loop.

0

Making a thread just for a loop seems wasteful, I think in this case an event is better and cleaner. @Neon_isHere

I like where @Gnossien is taking this and I would like to have a more specific / efficient solution:

local hum = script.Parent:FindFirstChild("Humanoid")

hum.HealthChanged:Connect(function(newHealth) -- The humanoid actually has a listener that awaits for HealthChange also make sure to avoid deprecated things
	if newHealth <= 50 then
    	hum.Health = 100
	end
end

I've changed small things but it still in an improvement:

  1. Specifically awaiting change on a property with a provided listener

Since the Humanoid comes with a HealthChanged event you might as well use it rather then listening for any changes on the Humanoid. In general you want to keep your code specific

  1. :connect to :Connect

not much here but a lesson to be learned is to avoid deprecated methods and functions since Roblox may remove them at any moment (though it may not seem likely)

These are small changes but it's best to keep your code as clean as possible. I'm just adding on. Best of luck and I hope this helped you!

This discussion is preserved as it was. New answers, comments, and votes are closed.