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)
if newHealth <= 50 then
hum.Health = 100
end
end
I've changed small things but it still in an improvement:
- 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
- :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!
6 comments
I was gonna say that but yeah, guy who wrote this question kinda inexperienced :/
that's ok, he wants to learn
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
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.
You could also use spawn(function() so the code wouldn't yield at the loop.
Making a thread just for a loop seems wasteful, I think in this case an event is better and cleaner. @Neon_isHere