Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 5 years ago

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

Log in to vote
1
Answered by
Robowon1 323 Moderation Voter
5 years ago

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
0
I was gonna say that but yeah, guy who wrote this question kinda inexperienced :/ xxViralityxx -9 — 5y
0
that's ok, he wants to learn Robowon1 323 — 5y
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 EvilTony99 -7 — 5y
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. User#25069 0 — 5y
View all comments (2 more)
0
You could also use spawn(function() so the code wouldn't yield at the loop. Neon_isHere 100 — 5y
0
Making a thread just for a loop seems wasteful, I think in this case an event is better and cleaner. @Neon_isHere CeramicTile 847 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

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!

Answer this question