XP bar not reseting to 0 once level up intead it just continues

Hey!

I currently have a level script by HowToRoblox. I have edited it to my preference but, there’s an issue, I want the xp bar to reset to 0 but, it won’t work it just continues adding xp.

local DataStoreService = game:GetService("DataStoreService")
local SaveDataStore = DataStoreService:GetDataStore("SaveData96")


local function SavePlayerData(player)
	
	local success, errormsg = pcall(function()
	
		local SaveData = {}
		
		for i, stats in pairs(player.leaderstats:GetChildren()) do
			
			SaveData[stats.Name] = stats.Value
		end	
		SaveDataStore:SetAsync(player.UserId, SaveData)
	end)
	
	if not success then 
		return errormsg
	end			
end	


Players.PlayerAdded:Connect(function(player)
	
	local Statsss = player:WaitForChild("leaderstats")
	
	local level = player:WaitForChild("leaderstats").Level
	
	local experience = Instance.new("IntValue")
	experience.Name = "TotalXP"
	experience.Value = 0
	experience.Parent = player
	

	local Data = SaveDataStore:GetAsync(player.UserId)
	
	if Data then
		
		for i, stats in pairs(Statsss:GetChildren()) do
			
			stats.Value = Data[stats.Name]
		end		
			
	else		
		print(player.Name .. " has no data.")			
	end
			
	
	local expToLevelUp
		
	local expForPreviousLevel = 0
	
	
	while wait() do
		
		local levelBar = player.PlayerGui:WaitForChild("LevelBar")	
		
		if level.Value < 1 then 
			
			expToLevelUp = 100 
			
		else
			
			expToLevelUp = math.floor(level.Value ^ 1.3) * 200 + math.floor(level.Value ^ 4)
		end
		
		
		if experience.Value >= expToLevelUp then
			
			level.Value = level.Value + 1	
		end
		
		expForPreviousLevel = math.floor((level.Value - 1) ^ 1.3) * 200 + math.floor((level.Value - 1) ^ 4)
		
		
		local expDifference = expToLevelUp + expForPreviousLevel

		local expDifference2 = experience.Value + expForPreviousLevel
			
		
		levelBar.Bar:TweenSize(UDim2.new(levelBar.BarBackground.Size.X.Scale * (expDifference2 / expDifference), 0, levelBar.BarBackground.Size.Y.Scale, 0), Enum.EasingDirection.InOut, Enum.EasingStyle.Quint, 0.001)
		
		levelBar.Experience.Text = expDifference2 .. "/" .. expDifference
		
		levelBar.Level.Text = "Level: " .. level.Value

	end			
end)


Players.PlayerRemoving:Connect(function(player)
	
	local errormsg = SavePlayerData(player)
	
	if errormsg then	
		warn(errormsg)		
	end	
end)

game:BindToClose(function()
	for i, player in pairs(Players:GetPlayers()) do	
		
		local errormsg = SavePlayerData(player)
		if errormsg then
			warn(errormsg)
		end			
	end
	wait(2)	
end)

How can this be fixed?

if experience.Value >= expToLevelUp then
experience.Value=0 – Since you want to set it to 0
level.Value = level.Value + 1
end

1 Like

@ElectricalSpy, unfortunately this did not work for me. I got an output error that said

attempt to compare nil <= number

Any idea on how can this be fixed?

@ElectricalSpy, thank you. I just realized I misplaced the script you send me.