Why don't definitions work properly with UDim2?

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)
end

humanoid.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.

Remove «.Size » at the end of « local barSise »
Use barSize.Size = after

Because you are not changing the actual bar size but you are changing the variable « barSize »

variable can be copies or references to the values that they are assigned to based on the programming language and data type

for bar size you are just editing a copy UDim2 and not the actual UDim2 that controls the size of the bar

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.