In short
Put a Script in ServerScriptService that adds a leaderstats folder with Level and XP IntValues to each player. Give XP only on the server. When XP reaches the amount the next level needs, for example 100 * level ^ 1.5, subtract it and add 1 to Level. Load both numbers from a data store when the player joins and save them when they leave.
- Store the XP inside the current level, not the total, so the bar is simply XP divided by what the next level needs.
- Use a loop, not an if, for level-ups: a big reward can be worth more than one level.
- Never save a player whose data failed to load, or a short outage resets them to level 1.
Get the script
XP and level system with saving
One server Script: Level and XP on the player list, a level-up formula, XP from any server script through a BindableEvent, and saving with a data store.
-- Script in ServerScriptService named XpLevels.
-- Level and XP on leaderstats, a level-up formula, XP from other server scripts, saved in a data store.
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local BASE_XP = 100 -- XP from level 1 to level 2
local GROWTH = 1.5 -- how fast each level gets more expensive
local MAX_LEVEL = 100
local STORE_NAME = "PlayerLevels_v1"
local AUTOSAVE_SECONDS = 120
type LevelData = { Level: number, Xp: number }
-- Players whose saved data loaded. Anyone missing is never saved, so a failed load
-- cannot overwrite real progress with level 1.
local loaded: { [Player]: boolean } = {}
local function levelStore(): DataStore
return DataStoreService:GetDataStore(STORE_NAME)
end
local function keyFor(player: Player): string
return "player_" .. player.UserId
end
local function xpForLevel(level: number): number
return math.floor(BASE_XP * level ^ GROWTH)
end
-- Other server scripts give XP with: ServerStorage.AwardXp:Fire(player, 25)
local awardXp: BindableEvent
local existingEvent = ServerStorage:FindFirstChild("AwardXp")
if existingEvent and existingEvent:IsA("BindableEvent") then
awardXp = existingEvent
else
awardXp = Instance.new("BindableEvent")
awardXp.Name = "AwardXp"
awardXp.Parent = ServerStorage
end
local function getStats(player: Player): (IntValue?, IntValue?)
local leaderstats = player:FindFirstChild("leaderstats")
local level = leaderstats and leaderstats:FindFirstChild("Level")
local xp = leaderstats and leaderstats:FindFirstChild("XP")
if level and level:IsA("IntValue") and xp and xp:IsA("IntValue") then
return level, xp
end
return nil, nil
end
-- The XP bar reads this attribute so it knows how full to draw itself
local function updateNeeded(player: Player, level: number)
player:SetAttribute("XpNeeded", if level >= MAX_LEVEL then 0 else xpForLevel(level))
end
local function addXp(player: Player, amount: number)
local level, xp = getStats(player)
if not (level and xp) then
return
end
-- Only whole, positive, real numbers: NaN and infinity fail these checks
if amount ~= amount or amount <= 0 or amount == math.huge then
return
end
if level.Value >= MAX_LEVEL then
return
end
local total = xp.Value + math.floor(amount)
local newLevel = level.Value
-- A loop, because one big reward can be worth several levels
while newLevel < MAX_LEVEL and total >= xpForLevel(newLevel) do
total -= xpForLevel(newLevel)
newLevel += 1
end
if newLevel >= MAX_LEVEL then
total = 0
end
if newLevel > level.Value then
print(player.Name .. " reached level " .. newLevel)
end
level.Value = newLevel
xp.Value = total
updateNeeded(player, newLevel)
end
local function onPlayerAdded(player: Player)
-- Reuse the folder if another script (coins, say) already made it
local leaderstats: Instance
local existing = player:FindFirstChild("leaderstats")
if existing then
leaderstats = existing
else
leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
end
local ok, data = pcall(function()
return levelStore():GetAsync(keyFor(player))
end)
local level = Instance.new("IntValue")
level.Name = "Level"
level.Value = 1
local xp = Instance.new("IntValue")
xp.Name = "XP"
xp.Value = 0
if ok then
if type(data) == "table" then
level.Value = math.clamp(math.floor(tonumber(data.Level) or 1), 1, MAX_LEVEL)
xp.Value = math.max(0, math.floor(tonumber(data.Xp) or 0))
end
loaded[player] = true
else
warn("Could not load levels for " .. player.Name .. ": " .. tostring(data))
end
level.Parent = leaderstats
xp.Parent = leaderstats
updateNeeded(player, level.Value)
end
local function save(player: Player)
if not loaded[player] then
return
end
local level, xp = getStats(player)
if not (level and xp) then
return
end
local data: LevelData = { Level = level.Value, Xp = xp.Value }
local ok, err = pcall(function()
levelStore():SetAsync(keyFor(player), data, { player.UserId })
end)
if not ok then
warn("Could not save levels for " .. player.Name .. ": " .. tostring(err))
end
end
awardXp.Event:Connect(function(player: unknown, amount: unknown)
if typeof(player) == "Instance" and player:IsA("Player") and type(amount) == "number" then
addXp(player, amount)
end
end)
Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAdded, player)
end
Players.PlayerRemoving:Connect(function(player: Player)
save(player)
loaded[player] = nil
end)
-- Save everyone every few minutes, so a server crash loses little
task.spawn(function()
while true do
task.wait(AUTOSAVE_SECONDS)
for _, player in Players:GetPlayers() do
task.spawn(save, player)
end
end
end)
-- When the server shuts down, save everyone before it closes
game:BindToClose(function()
local pending = 0
for _, player in Players:GetPlayers() do
pending += 1
task.spawn(function()
save(player)
pending -= 1
end)
end
while pending > 0 do
task.wait()
end
end)
RoCode builds it in the place you have open in Roblox Studio, on Windows or macOS with a desktop browser; on a phone the button sends the prompt and the link to your computer. Free to start, with free credits every day. More Roblox Studio scripts
Where to put it
ServerScriptService
XpLevels Script new
ServerStorage
AwardXp BindableEvent (made by the script)
Settings you can change
BASE_XPIn the script- XP needed to go from level 1 to level 2. Every later level needs more. Default:
100. GROWTHIn the script- How fast the XP needed grows. 1 means every level costs more by the same amount, 2 makes high levels very slow. Default:
1.5. MAX_LEVELIn the script- The highest level. XP stops counting once a player reaches it. Default:
100.
Saving only works in Studio after you publish the place and turn on Enable Studio Access to API Services (Step 5). Without it the levels still work, they just reset every session.
What a cheater can and cannot doXP is only given by server scripts through a BindableEvent in ServerStorage, which clients cannot see or fire, so a cheater cannot give themselves levels. If you add a RemoteEvent that leads to XP, check on the server that the player really did the thing (Step 3).
Type-checked with luau-lsp strict against Roblox's API definitions on 14 November 2026. Not playtested in Studio yet: press Play and watch the Output window before you publish.
Prompt for RoCode
Add an XP and level system to my game: one Script in ServerScriptService with Level and XP in leaderstats, XP needed for the next level of 100 times level to the power 1.5, a max level of 100, an AwardXp BindableEvent in ServerStorage that other server scripts fire with a player and an amount, and saving with a data store that never saves a player whose data failed to load.
On this page
How an XP and level system works
Each player has two numbers: their Level and their XP towards the next level. When something good happens, a server script adds XP. If the XP is now at least what the next level needs, the script takes that amount away and adds one level. The leftover XP carries over, so nothing is lost.
Both numbers sit in a folder named leaderstats inside the Player. Roblox shows any IntValue in that folder on the player list in the top-right corner, which gives you a level column for free. The same numbers are saved to a data store, so a level 12 player is still level 12 tomorrow.
| Level | XP to reach the next level | Total XP from level 1 to the next level |
|---|---|---|
| 1 | 100 | 100 |
| 2 | 282 | 382 |
| 5 | 1,118 | 2,819 |
| 10 | 3,162 | 14,264 |
| 25 | 12,500 | 131,300 |
Step 1: Pick a level-up formula
The formula decides how long your game feels. A flat amount per level (say 100 XP every time) makes levels arrive at the same pace forever, so they stop feeling special. Most games make each level cost more than the last. This guide uses a power curve:
-- XP needed to go from this level to the next one
local BASE_XP = 100
local GROWTH = 1.5
local function xpForLevel(level: number): number
return math.floor(BASE_XP * level ^ GROWTH)
end
print(xpForLevel(1)) --> 100
print(xpForLevel(10)) --> 3162
- BASE_XP sets the size of the first level. If your quests give 25 XP, a BASE_XP of 100 means four quests for level 2.
- GROWTH sets the curve. At 1 the cost rises in a straight line (100, 200, 300). At 1.5 it rises faster. At 2, level 50 needs a quarter of a million XP, which only suits games played for months.
- Run the test script and print a few levels before you choose. Delete it afterwards.
Step 2: The XP and level script
- Hover over ServerScriptService in the Explorer, click + and insert a Script. Name it
XpLevels. - Paste the code below. It makes the
AwardXpBindableEvent in ServerStorage by itself. - If you already have a leaderstats script (for Coins, say), keep it: this script adds Level and XP to the same folder instead of making a second one.
-- Script in ServerScriptService named XpLevels.
-- Level and XP on leaderstats, a level-up formula, XP from other server scripts, saved in a data store.
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local BASE_XP = 100 -- XP from level 1 to level 2
local GROWTH = 1.5 -- how fast each level gets more expensive
local MAX_LEVEL = 100
local STORE_NAME = "PlayerLevels_v1"
local AUTOSAVE_SECONDS = 120
type LevelData = { Level: number, Xp: number }
-- Players whose saved data loaded. Anyone missing is never saved, so a failed load
-- cannot overwrite real progress with level 1.
local loaded: { [Player]: boolean } = {}
local function levelStore(): DataStore
return DataStoreService:GetDataStore(STORE_NAME)
end
local function keyFor(player: Player): string
return "player_" .. player.UserId
end
local function xpForLevel(level: number): number
return math.floor(BASE_XP * level ^ GROWTH)
end
-- Other server scripts give XP with: ServerStorage.AwardXp:Fire(player, 25)
local awardXp: BindableEvent
local existingEvent = ServerStorage:FindFirstChild("AwardXp")
if existingEvent and existingEvent:IsA("BindableEvent") then
awardXp = existingEvent
else
awardXp = Instance.new("BindableEvent")
awardXp.Name = "AwardXp"
awardXp.Parent = ServerStorage
end
local function getStats(player: Player): (IntValue?, IntValue?)
local leaderstats = player:FindFirstChild("leaderstats")
local level = leaderstats and leaderstats:FindFirstChild("Level")
local xp = leaderstats and leaderstats:FindFirstChild("XP")
if level and level:IsA("IntValue") and xp and xp:IsA("IntValue") then
return level, xp
end
return nil, nil
end
-- The XP bar reads this attribute so it knows how full to draw itself
local function updateNeeded(player: Player, level: number)
player:SetAttribute("XpNeeded", if level >= MAX_LEVEL then 0 else xpForLevel(level))
end
local function addXp(player: Player, amount: number)
local level, xp = getStats(player)
if not (level and xp) then
return
end
-- Only whole, positive, real numbers: NaN and infinity fail these checks
if amount ~= amount or amount <= 0 or amount == math.huge then
return
end
if level.Value >= MAX_LEVEL then
return
end
local total = xp.Value + math.floor(amount)
local newLevel = level.Value
-- A loop, because one big reward can be worth several levels
while newLevel < MAX_LEVEL and total >= xpForLevel(newLevel) do
total -= xpForLevel(newLevel)
newLevel += 1
end
if newLevel >= MAX_LEVEL then
total = 0
end
if newLevel > level.Value then
print(player.Name .. " reached level " .. newLevel)
end
level.Value = newLevel
xp.Value = total
updateNeeded(player, newLevel)
end
local function onPlayerAdded(player: Player)
-- Reuse the folder if another script (coins, say) already made it
local leaderstats: Instance
local existing = player:FindFirstChild("leaderstats")
if existing then
leaderstats = existing
else
leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
end
local ok, data = pcall(function()
return levelStore():GetAsync(keyFor(player))
end)
local level = Instance.new("IntValue")
level.Name = "Level"
level.Value = 1
local xp = Instance.new("IntValue")
xp.Name = "XP"
xp.Value = 0
if ok then
if type(data) == "table" then
level.Value = math.clamp(math.floor(tonumber(data.Level) or 1), 1, MAX_LEVEL)
xp.Value = math.max(0, math.floor(tonumber(data.Xp) or 0))
end
loaded[player] = true
else
warn("Could not load levels for " .. player.Name .. ": " .. tostring(data))
end
level.Parent = leaderstats
xp.Parent = leaderstats
updateNeeded(player, level.Value)
end
local function save(player: Player)
if not loaded[player] then
return
end
local level, xp = getStats(player)
if not (level and xp) then
return
end
local data: LevelData = { Level = level.Value, Xp = xp.Value }
local ok, err = pcall(function()
levelStore():SetAsync(keyFor(player), data, { player.UserId })
end)
if not ok then
warn("Could not save levels for " .. player.Name .. ": " .. tostring(err))
end
end
awardXp.Event:Connect(function(player: unknown, amount: unknown)
if typeof(player) == "Instance" and player:IsA("Player") and type(amount) == "number" then
addXp(player, amount)
end
end)
Players.PlayerAdded:Connect(onPlayerAdded)
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAdded, player)
end
Players.PlayerRemoving:Connect(function(player: Player)
save(player)
loaded[player] = nil
end)
-- Save everyone every few minutes, so a server crash loses little
task.spawn(function()
while true do
task.wait(AUTOSAVE_SECONDS)
for _, player in Players:GetPlayers() do
task.spawn(save, player)
end
end
end)
-- When the server shuts down, save everyone before it closes
game:BindToClose(function()
local pending = 0
for _, player in Players:GetPlayers() do
pending += 1
task.spawn(function()
save(player)
pending -= 1
end)
end
while pending > 0 do
task.wait()
end
end)
What the script does
- leaderstats: Level and XP show on the player list. If another script already made the folder, the two values are added to it.
- addXp: adds the XP, then levels up as many times as the XP pays for. At MAX_LEVEL the XP is held at 0.
- XpNeeded attribute: the server writes the XP the next level needs onto the Player, so the XP bar never has to copy the formula.
- loaded: a player is only saved if their data loaded. If the data store was down when they joined, they play on a fresh level 1 for that session, but their real save is not overwritten.
- Autosave and BindToClose: everyone is saved every 2 minutes and when the server shuts down, as well as when they leave.
Step 3: Give XP from other scripts
The level script owns the numbers. Any other server script hands out XP by firing the AwardXp BindableEvent with a player and an amount. A BindableEvent only works between scripts on the same side, and ServerStorage is never sent to players, so clients cannot fire it.
Here is a complete example: parts tagged XpOrb give 25 XP when a player touches them, then hide for 10 seconds.
-- Script in ServerScriptService named XpOrbs.
-- Parts tagged "XpOrb" give XP on touch, then come back after a while.
local CollectionService = game:GetService("CollectionService")
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local XP_PER_ORB = 25
local RESPAWN_SECONDS = 10
local awardXp = ServerStorage:WaitForChild("AwardXp") :: BindableEvent
local function setUpOrb(orb: Instance)
if not orb:IsA("BasePart") then
return
end
local ready = true
orb.Touched:Connect(function(hit: BasePart)
if not ready then
return
end
local character = hit.Parent
local player = if character and character:IsA("Model") then Players:GetPlayerFromCharacter(character) else nil
if not player then
return
end
ready = false
orb.Transparency = 1
orb.CanTouch = false
awardXp:Fire(player, XP_PER_ORB)
task.delay(RESPAWN_SECONDS, function()
orb.Transparency = 0
orb.CanTouch = true
ready = true
end)
end)
end
for _, orb in CollectionService:GetTagged("XpOrb") do
setUpOrb(orb)
end
CollectionService:GetInstanceAddedSignal("XpOrb"):Connect(setUpOrb)
The same one line, awardXp:Fire(player, amount), works from a quest script, a round system that rewards the winner, or a kill tracker. For the kill version, see the kill feed guide, which finds out who landed the final hit.
Step 4: Show an XP bar
The player list shows the numbers, but a bar is what makes players chase the next level. This LocalScript builds a small bar at the bottom of the screen in code, so there is nothing to draw by hand. It only reads the values, so it is safe on the client.
- Hover over StarterGui, click + and insert a LocalScript. Name it
XpBar. - Paste the code below and press Play.
-- LocalScript in StarterGui named XpBar.
-- Draws "Level 3" and a bar that fills as the player earns XP. It only reads values.
local Players = game:GetService("Players")
local TweenService = game:GetService("TweenService")
local player = Players.LocalPlayer
local leaderstats = player:WaitForChild("leaderstats")
local level = leaderstats:WaitForChild("Level") :: IntValue
local xp = leaderstats:WaitForChild("XP") :: IntValue
local gui = Instance.new("ScreenGui")
gui.Name = "XpBarGui"
gui.ResetOnSpawn = false
local back = Instance.new("Frame")
back.AnchorPoint = Vector2.new(0.5, 1)
back.Position = UDim2.new(0.5, 0, 1, -16)
back.Size = UDim2.fromOffset(320, 22)
back.BackgroundColor3 = Color3.fromRGB(30, 30, 40)
back.Parent = gui
Instance.new("UICorner").Parent = back
local fill = Instance.new("Frame")
fill.Size = UDim2.fromScale(0, 1)
fill.BackgroundColor3 = Color3.fromRGB(120, 90, 255)
fill.Parent = back
Instance.new("UICorner").Parent = fill
local label = Instance.new("TextLabel")
label.Size = UDim2.fromScale(1, 1)
label.BackgroundTransparency = 1
label.TextColor3 = Color3.new(1, 1, 1)
label.Font = Enum.Font.GothamBold
label.TextSize = 14
label.Parent = back
gui.Parent = player:WaitForChild("PlayerGui")
local function refresh()
local needed = player:GetAttribute("XpNeeded")
if type(needed) ~= "number" or needed <= 0 then
-- Max level, or the server has not sent the number yet
fill.Size = UDim2.fromScale(1, 1)
label.Text = "Level " .. level.Value
return
end
local ratio = math.clamp(xp.Value / needed, 0, 1)
TweenService:Create(fill, TweenInfo.new(0.25), { Size = UDim2.fromScale(ratio, 1) }):Play()
label.Text = "Level " .. level.Value .. " " .. xp.Value .. " / " .. needed .. " XP"
end
level.Changed:Connect(refresh)
xp.Changed:Connect(refresh)
player:GetAttributeChangedSignal("XpNeeded"):Connect(refresh)
refresh()
ResetOnSpawn = false keeps the bar on screen when the character respawns. The bar reads XpNeeded from the Player's attributes, which only the server sets, so if you change the formula on the server the bar follows. To make the bar match the rest of your game, change the two Color3 values.
Step 5: Test it in Studio
- Open the Output window (Window, then Output) and press Play. Level 1 and XP 0 appear on the player list.
- Tag a few parts
XpOrband touch them. XP goes up by 25 each time, and on the fourth orb you reach level 2 with 0 XP left. - To test big jumps, open the Command Bar while playing (on the Server view) and run
game.ServerStorage.AwardXp:Fire(game.Players:GetPlayers()[1], 5000). You should jump several levels at once. - Stop, press Play again, and check your level came back. If it did not, look for a "Could not load" or "Could not save" warning in the Output.
Ideas to build on it
- Rewards per level: when
newLevelis greater than the old level inaddXp, give coins or unlock a tool there. - Level gates: a door that only opens at level 10 checks
leaderstats.Level.Valueon the server. The door guide shows where to put that check. - Prestige: let max-level players reset for a permanent bonus. The rebirth system guide builds that for coins, and the same pattern works for levels.
- A top 10 board: an OrderedDataStore of levels, as in the leaderboard guide.
This script saves with SetAsync and the "only save if loaded" rule, which is safe for most games. If players can join two servers quickly (for example through teleports), read about session locking in the DataStore tutorial.
Common errors and fixes
Most problems show up in the Output window as a red or orange line. Check it first.
Level and XP do not show on the player list
The folder must be named exactly leaderstats, all lower case, and be inside the Player (not the character). Check that XpLevels is a Script in ServerScriptService, not a LocalScript.
The level resets every time I play
Saving is off in Studio until you publish and turn on Enable Studio Access to API Services. In the Output you will see "Could not load levels". In a published game it saves without this step.
Firing AwardXp does nothing
Fire it from a server Script, not a LocalScript: a LocalScript cannot see ServerStorage. The player must be a Player object, not a character, and the amount must be a number above 0.
Infinite yield possible on ServerStorage:WaitForChild("AwardXp")
The XpLevels script makes the event when it starts. If it is disabled, deleted or has an error above that line, other scripts wait forever. See Infinite yield possible.
Build it with RoCode
If you would rather not wire this up by hand, RoCode can build it in the place you have open. RoCode is an independent AI agent for Roblox Studio, not made by Roblox: you describe the change in a web chat, and its Studio plugin creates the scripts in your Explorer.
Add levels to my game: XP and Level on the leaderboard, 25 XP for each coin and 100 for winning a round, an XP bar at the bottom of the screen, and save it all.
- Can read your place first to find your coin and round scripts, then adds the XP calls to them
- Writes the scripts with Create Script and is told to compile-check each one with Check Script
- Sets an undo point before and after each batch of changes, so Ctrl+Z steps back one batch at a time
Saving still needs Studio access to API Services turned on, which only you can do in Experience Settings. How RoCode connects to Studio.
Questions
How do I make a level system in Roblox Studio?
Add Level and XP IntValues to a leaderstats folder in a server Script, add XP on the server, and level up when XP reaches what the next level needs. Step 2 has the whole script.
What is a good XP formula for Roblox?
BASE_XP * level ^ GROWTH with 100 and 1.5 is a common start: 100 XP for level 2, about 3,200 for level 11. Lower GROWTH for faster levels.
How do I save levels in Roblox?
Save Level and XP to a data store with SetAsync when the player leaves and when the server closes, and load them with GetAsync when they join, both inside pcall.
How do I give XP when a player kills someone?
Find the killer from the creator tag on the Humanoid when it dies, then fire AwardXp with that player. The kill feed guide builds the tag part.
Can I make the XP bar with a LocalScript?
Yes, for showing it. The LocalScript in Step 4 only reads values. Changing XP from a LocalScript would not reach the server or save.
Sources and further reading
- Roblox Creator Docs: In-experience leaderboards. the leaderstats folder and which values it shows
- Roblox Creator Docs: Data stores. GetAsync, SetAsync and Studio access
- Roblox Creator Docs: BindableEvent. events between scripts on the same side
- Roblox Creator Docs: DataModel.BindToClose. saving when the server shuts down
How the code was checked: every script on this page passes Luau's strict type checker against Roblox's API definitions (luau-lsp, 14 November 2026). A type check catches misspelt APIs and wrong types, not game logic, so playtest in Studio before you publish.