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

Why does this script play the tween even though this if statement should be false?

Hi. I'm trying to detect when a player's health goes down. When it does, a bar appears with the size of their old health/100. it then tweens away to transparent. This works, but for some reason the tween is not behaving properly. The bar disappears very quickly, even with the extreme values I put in the tweeninfo that tell it to take 6 seconds to disappear.

local player = game.Players.LocalPlayer
local healthgui = script.Parent.Parent.Parent
local bar = script.Parent
local bg = bar.Parent.Background
local tweenservice = game:GetService("TweenService")
local tweeninfo = TweenInfo.new(4, Enum.EasingStyle.Cubic, Enum.EasingDirection.In, 0, false, 2)
local tween = tweenservice:Create(bg, tweeninfo, {Transparency = 1})

player.CharacterAdded:Connect(function(char)
	local hum = char:WaitForChild("Humanoid")
	
	bar.Size = UDim2.new(1,0,1,0)
	local lasthealth = 100 --reset
	hum.HealthChanged:connect(function(health)
		if health == 100 or health == 0 then
			healthgui.Enabled = false
		else
			bg.Size = UDim2.new((lasthealth/100), 0, 1, 0) --resize to old health
			if health < lasthealth then
				tween:Cancel()
				--update background
				bg.BackgroundTransparency = 0.8
				tween:Play()
				print(lasthealth, health, tween.PlaybackState)
				lasthealth = health
			end
			healthgui.Enabled = true
			bar.Size = UDim2.new(math.clamp(health/100, 0, 1),0,1,0)
			bar.BackgroundColor3 = Color3.fromHSV((math.clamp(health/100,0,1))/3,1,1)
		end
	end)
end)

1 answer

✓ Accepted answer

On line 07, I believe you meant to put {BackgroundTransparency = 1}, instead of {Transparency = 1}. This could solve your problem.

1 comment

0

Good catch! That probably helped. I found the issue was that bg.size was being set outside of the if statement so it would resize on health update. At least, I think. It works now!

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