Looking for a way to make a UI appear and disappear

I have a Stamina Bar and when it reaches 100% i want it to disappear so it doesn’t get in the players way… the only issue is it will appear when being used but only when the player has let go of the sprint key.

but i want it to instantly return once the player hits the sprint key. Here’s my code (any help is very appreciated)

–{{ Services }}–
local UIS = game:GetService(“UserInputService”)
local RS = game:GetService(“RunService”)

–{{ Variables }}}–
– Player –
local player = game.Players.LocalPlayer
local character = player.Character or player.Character:Wait()
local hum = character:WaitForChild(“Humanoid”)
local playerGui = player.PlayerGui

– Settings -
local stam = 100
local maxStam = 100

local speedDif = 40
local DrainRate = 30
local refreshRae = 1
local stamRefresh = 5

– Booleans ==
local sprinting = false
local sprintingHeld = false
local exhausted = false
local default = false

local Stamina =playerGui.PlayerStatus.BehindStam.Stamina
local StaminaBehind =playerGui.PlayerStatus.BehindStam

–{{ Function }}–
local function sprint(active)
if exhausted then return end

hum.WalkSpeed = active and hum.WalkSpeed + speedDif or hum.WalkSpeed - speedDif
sprinting = active

end

local function onInput(input)
if input.KeyCode == Enum.KeyCode.LeftControl and input.UserInputType ~= Enum.UserInputType.Gamepad1 then
sprintingHeld = input.UserInputState == Enum.UserInputState.Begin
sprint(sprintingHeld)
end
end

local function updateStaminaUI()
playerGui.PlayerStatus.BehindStam.Stamina.Size = UDim2.new(1, 0, math.clamp(stam / maxStam, 0, 1), 1)
end

UIS.InputBegan:Connect(onInput)
UIS.InputEnded:Connect(onInput)

RS.Heartbeat:Connect(function(deltaTime)

if sprinting then
	stam = math.max(0, stam - DrainRate * deltaTime)
	updateStaminaUI()
	print(math.floor(stam))
	if stam == 0 then
		sprint(false)
		exhausted = true
		if exhausted == true then
			hum.WalkSpeed = 16
		end
	end
else
	stam = math.min(100, stam + refreshRae * deltaTime)
	if stam >= stamRefresh then
		updateStaminaUI()
		if stam <= 99 then 
			StaminaBehind.Visible = true
		end
		if stam >= 100 then
			StaminaBehind.Visible = false
		end
		exhausted = false
		print(math.floor(stam))
		if sprintingHeld then
			sprint(true)
		end
	end
end

end)

Move the if statements that control the stamina bar visibility outside of the “sprinting” if statement. When you paste code on the DevForum, add a pair of three backticks (`) around the entire script so it’s formatted properly.

2 Likes

You should tween the transparency to make it more smooth, instead of it just popping up on your screen.

1 Like

thank you for the formatting tip ill keep that in mind in the future… and your solution worked :slight_smile:

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