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

Need help with my health bar script. Works perfect in studio, not in live game?

I'm trying to make a custom health bar for a game I'm making. The script runs perfectly when I test it in studio, but once i try on roblox's website, it messes up. Once i die, the health bar doesn't go down until after I respawn and it just stays down even though i'm alive.

Here is the script for any interested-

  1. local plr = game.Players.LocalPlayer.Character
  2. while true do
  3. script.Parent:TweenSize(UDim2.new(plr.Humanoid.Health/plr.Humanoid.MaxHealth, 0, 1, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1)
  4. wait(0.1)
  5. end

1 comment

0

Use code blocks, instead.

1 answer

You shouldn't use a while-loop. There's an event that fires each time the health changes. You can find it by clicking here.

Also, when the character respawns, the variable plr doesn't automatically update. Instead, there's another event specifically for when the character respawns, found here.

This is how you should make the script:

local plr = game:GetService("Players").LocalPlayer -- The GetService method is a more efficient way of getting services (such as the Players service).
plr.CharacterAdded:Connect(function(newChar) -- Assign a function to a connection that runs each time the character respawns (with the newly made character as a new variable).
    newChar.Humanoid.HealthChanged:Connect(function(newHP) -- Another connection that runs each time the health changes with the new health as the variable.
        script.Parent:TweenSize(UDim2.new(newHP/newChar.Humanoid.MaxHealth, 0, 1, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1)
    end)
end)

I hope you've learned how to use events and consider using them in the future!

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