Exp bar goes outside the bar

Hello. I’m trying to make an exp bar but whenever the exp is greater than the xp needed it keeps going.
What’s the issue with my code?

local RepStore = game:GetService("ReplicatedStorage")

local ExpUpdated = RepStore:WaitForChild("RebUpdated")

local Frame = script.Parent

local Bar = Frame:WaitForChild("Bar")
local Exp = Frame:WaitForChild("Exp")

local BarExp = Bar:WaitForChild("BarExp")

BarExp.Size = UDim2.new(0, Frame.AbsoluteSize.X, 0.7, 0)

ExpUpdated.OnClientEvent:Connect(function(exp, expNeeded)
	Exp.Text = exp.."/"..expNeeded
	BarExp.Text = Exp.Text
	Bar:TweenSize(UDim2.new(exp / expNeeded, 0, 1, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.05, true)
end)
1 Like

There is no issue with your code.

To prevent a number to surpass a certain limit either bigger or smaller you would use math.clamp

I’ll implement math.clamp to your code right below

local RepStore = game:GetService("ReplicatedStorage")

local ExpUpdated = RepStore:WaitForChild("RebUpdated")

local Frame = script.Parent

local Bar = Frame:WaitForChild("Bar")
local Exp = Frame:WaitForChild("Exp")

local BarExp = Bar:WaitForChild("BarExp")

BarExp.Size = UDim2.new(0, Frame.AbsoluteSize.X, 0.7, 0)

ExpUpdated.OnClientEvent:Connect(function(exp, expNeeded)
	local exp = math.clamp(exp, 0, 1)
	Exp.Text = exp.."/"..expNeeded
	BarExp.Text = Exp.Text
	Bar:TweenSize(UDim2.new(exp / expNeeded, 0, 1, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.05, true)
end)

I set minimum to 0 and maximum to 1. Adjust it to your preferences.

Basically it’s this:

math.clamp(x, y, z)

x is the value you want to clamp
y is the minimum value x can be
z is the maximum value x can be

1 Like

Hey, Sorry for the dead ping but do you know any reason why my code is not working i have never worked with math.clamp

local Exp = game.Players.LocalPlayer:WaitForChild("Data"):WaitForChild("Exp") 
local expmax = game.Players.LocalPlayer:WaitForChild("Data"):WaitForChild("ExpMax") 
local Bar = script.Parent.Parent

wait(2)
script.Parent.UpperBar.Size = UDim2.new((Exp.Value / expmax.Value), 0, 1, 0)

Exp.Changed:Connect(function()
	local exp = math.clamp(Exp.Value,0,1)
	script.Parent.UpperBar.Size = UDim2.new((Exp.Value / expmax.Value), 0, 1, 0)
end)

expmax.Changed:Connect(function()
	local exp = math.clamp(Exp.Value,0,1)
	script.Parent.UpperBar.Size = UDim2.new((Exp.Value / expmax.Value), 0, 1, 0)
end)

Exp.Changed:Connect(function()
local exp = math.clamp(Exp.Value,0,1)
script.Parent.UpperBar.Size = UDim2.new((exp / expmax.Value), 0, 1, 0)
end)

expmax.Changed:Connect(function()
local exp = math.clamp(Exp.Value,0,1)
script.Parent.UpperBar.Size = UDim2.new((exp / expmax.Value), 0, 1, 0)
end)