How to keep leftover XP

I have script where the player can get xp and levels up based on how much they have. I added coins but the problem is after they level up it resets back to zero. I have tried different ways but it doesn’t work.

local level = 1
local exp = 0
local axp = 20
local coins = 0

local InStudio = game:GetService("RunService"):IsStudio()

if not InStudio then
	level = game:GetService("DataStoreService"):GetDataStore("Levels")
	exp = game:GetService("DataStoreService"):GetDataStore("EXP")
	axp = game:GetService("DataStoreService"):GetDataStore("AXP") -- Amount of exp needed to level up.
	coins = game:GetService("DataStoreService"):GetDataStore("Coins")
end

function savedata(dataname, playerid, value)
	if InStudio then return end
	dataname:SetAsync(playerid, value)
end

game.Players.PlayerAdded:connect(function(player)
	local leader = Instance.new("Folder")
	leader.Name = "leaderstats"
	leader.Parent = player
	local levelz = Instance.new("IntValue")
	levelz.Name = "Level"
	local xpz = Instance.new("NumberValue")
	xpz.Name = "Exp"
	local xpn = Instance.new("IntValue")
	xpn.Name = "ExpNeeded"
	local Coinz = Instance.new("NumberValue")
	Coinz.Name = "Coins"

	if not InStudio then
		xpn.Value = axp:GetAsync(tostring(player.userId)) or 20
		xpz.Value = exp:GetAsync(tostring(player.userId)) or 0
		levelz.Value = level:GetAsync(tostring(player.userId)) or 1
		Coinz.Value = coins:GetAsync(tostring(player.userId)) or 0
	else
		xpn.Value = axp
		xpz.Value = exp
		levelz.Value = level
	end

	levelz.Parent = leader
	xpz.Parent = leader
	Coinz.Parent = leader
	xpn.Parent = leader
	

	xpz.Changed:connect(function()
		if player.leaderstats:WaitForChild("Exp").Value >= player.leaderstats:WaitForChild("ExpNeeded").Value then
			levelz.Value = levelz.Value + 1

			xpn.Value = math.floor(xpn.Value * 1.5) 
			xpz.Value = 0 --this is the part where the xp resets to 0 regardless of how much xp you had earned before a level up

I don’t know how to fix it and reset it to zero

Just subtract the current exp by the needed exp and then set the needed exp after

levelz.Value += 1
			
xpz.Value -= xpn.Value
xpn.Value = math.floor(xpn.Value * 1.5) 

@Kostiskat I think that would work as well, but I think this one is also simple enough to do since it’s just a simple subtraction, but to each their own

1 Like

No need, just use the % operator to get the remainder of the total xp collected divided by the max xp required to level up.