Adding Remaining XP to XP Bar

I was wondering how I can get the remaining xp from someone when they level up. I have a fully functional level system with ui and I was wondering how I can add the remaining xp. For example if someone was level 1 and they got 100k xp it would go to level 500 or something, but for me it goes to level 2.

Here is the server code:

game.Players.PlayerAdded:Connect(function(plr)
	local ls = Instance.new("Folder", plr)
	ls.Name = "leaderstats"
	
	local XP = Instance.new("IntValue", ls)
	XP.Name = "XP"
	XP.Value = 0
	
	local MaxXP = Instance.new("IntValue", plr)
	MaxXP.Name = "MaxXP"
	MaxXP.Value = 100
	
	local Level = Instance.new("IntValue", ls)
	Level.Name = "Level"
	Level.Value = 1
	
	XP.Changed:Connect(function(val)
		if XP.Value >= MaxXP.Value then
			MaxXP.Value *= 1.25
			Level.Value += 1
			XP.Value = 0
		end
	end)
end)

and here is the client code:

local TS = game:GetService("TweenService")
local info = TweenInfo.new(0.5, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)

local plr = game.Players.LocalPlayer
local leaderstats = plr:WaitForChild("leaderstats")

local XP = leaderstats:WaitForChild("XP")
local Level = leaderstats:WaitForChild("Level")

local function changed()
	local fr = (XP.Value / (Level.Value * 100))
	
	TS:Create(XpBar, info, {Size = UDim2.fromScale(fr, 1)}):Play()
end

XP.Changed:Connect(changed)
Level.Changed:Connect(changed)

Any help would be appreciated!

XP.Changed:Connect(function(val)
	-- 2. changing the if to a while makes multi-leveling possible with the same logic
	while XP.Value >= MaxXP.Value do
		XP.Value -= MaxXP.Value
		-- 1. using minus equal will keep the xp carry-over instead of = 0

		MaxXP.Value *= 1.25
		Level.Value += 1
	end
end)
2 Likes

Thanks! it works good. Emtpy space…

Hey also I just noticed a problem with my calculations in the ui. For some reason when I’m in the double digits of levels the bar of my ui will go outside of the frame. Here is the code for it:

	local fr = (XP.Value / (Level.Value * 100))
	
	TS:Create(XpBar, info, {Size = UDim2.fromScale(fr, 1)}):Play()

Maybe something is wrong with local fr idk

There may be a race condition since you have two connections, two tweens will play as XP and Level simultaneously changed. If it is a Gui object maybe using :TweenSize with the override parameter set to true will solve this?

like this?

local function changed()
	local fr = (XP.Value / (Level.Value * 100))
	
	XpBar:TweenSize(UDim2.fromScale(fr, 1), Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, 0.5, false, false)
end

This doesn’t work and gives the error:

Unable to cast value to function

Nvm I got it to work by using

local function changed()
	TS:Create(XpBar, info, {Size = UDim2.fromScale(XP.Value/MaxXp.Value, 1)}):Play()
end
1 Like