So I am trying to code a health bar, and I am having a really confusing problem. Here is a simplified version the code I have so far:
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:wait()
local humanoid = character:WaitForChild(“Humanoid”)
local beforeHealth = humanoid.Health
local HighlightDelay = 2– function to handle health change
local function onHealthChanged()
local maxHealth = humanoid.MaxHealth
local currentHealth = humanoid.Health
local healthPercentage = currentHealth / maxHealth
local barSize = script.Parent.Bars.Health.bar.Size
local highlightSize = script.Parent.Bars.Health.highlight.Size
print(beforeHealth, currentHealth)barSize = UDim2.fromScale(healthPercentage,barSize.Y.Scale)
endhumanoid.HealthChanged:connect(onHealthChanged)
So the code above doesn’t work. Well it does, but the health bar’s size value doesn’t change. Everything else works. But the “barSize = UDim2.whatever” doesn’t do anything. No errors, no bar size change, nothing. The confusing part is that it works perfectly if I do it like this:
script.Parent.Bars.Health.bar.Size = uDim 2.fromScale(healthPercentage,barSize.Y.Scale)
But shouldn’t it be identical to the first method? What changes using a definition, over writing it out long-form? It should mean the exact same thing. I don’t want to write it out long-form like this because it would make the code messy, and I need to call it a few times in the full script.