I am using Datastore 2 to save the players Level. And I have a code that shows the player which level they are on a UI.
UI Code
local plr = game.Players.LocalPlayer -- gets the player
game.ReplicatedStorage.RemoteEvents.LevelXpRemote.OnClientEvent:Connect(function() -- when the LevelXpRemote remote Event is Fired
script.Parent.Holder.XPText.Text = plr.XP.Value.."/"..plr.MaxXP.Value -- sets the XPText to plr.XP.Value.."/"..plr.MaxXP.Value
script.Parent.Holder.LevelNumber.Text = plr.leaderstats.Level.Value -- sets the levelText to players level text
end)
DataStore2 Code
--btw I don't really know how to use this module so some of the comments might be wrong
local DataStore2 = require(1936396537) --gets the datastore2 module
local DefaultXP = 0 --sets the defaultXP to 0
local DefaultLevel = 1
--local DefaultMoney = 0
game.Players.PlayerAdded:Connect(function(plr) -- when a player joins
local XPDataStore = DataStore2("XP-",plr) -- sets the XPDataStore to their value I think lol.
local LevelDataStore = DataStore2("LEVEL-",plr)
--local MoneyDataStore = DataStore2("Money-",plr)
-- creates a leaderstat
local leaderstats = Instance.new("Folder"); leaderstats.Parent = plr ; leaderstats.Name = "leaderstats"
local XP = Instance.new("NumberValue"); XP.Parent = plr ; XP.Name = "XP"
local Level = Instance.new("NumberValue") ; Level.Parent = leaderstats ; Level.Name = "Level" ; Level.Value = DefaultLevel
local MaxXP = Instance.new("NumberValue") ; MaxXP.Parent = plr ; MaxXP.Name = "MaxXP" ; MaxXP.Value = Level.Value*50
--local Money = Instance.new("NumberValue") ; Money.Parent = leaderstats ; Money.Name = "Money"
-- fires everytime the XP value of the player changes
local function XPUpdated(UpdatedXPValue)
XP.Value = XPDataStore:Get(UpdatedXPValue) -- sets the XP.Value of the player to UpdatedXPValue
end
local function LevelUpdated(UpdatedLevelValue)
Level.Value = LevelDataStore:Get(UpdatedLevelValue)
end
--[[local function MoneyUpdated(UpdatedMoneyValue)
Money.Value = MoneyDataStore:Get(UpdatedMoneyValue)
end]]
XPUpdated(DefaultXP) -- fires XPUpdated
LevelUpdated(DefaultLevel)
--MoneyUpdated(DefaultMoney)
XPDataStore:OnUpdate(XPUpdated())
LevelDataStore:OnUpdate(LevelUpdated())
--MoneyDataStore:OnUpdate(MoneyUpdated())
end)
game.Players.PlayerRemoving:Connect(function(player) -- when the player leaves the game
local XPDataStore = DataStore2("XP-",player) -- saves their Xp to XPDataStore
XPDataStore:Set(player.XP.Value) --sets their XP to XPDataStore
local LevelDataStore = DataStore2("LEVEL-",player)
LevelDataStore:Set(player.leaderstats.Level.Value)
--local MoneyDataStore = DataStore2("Money-",player)
--MoneyDataStore:Set(player.leaderstats.Money.Value)
end)
It shows the players level as 2 but the UI says it’s 1. The code sometimes works and it shows 2 but breaks again. If I write this code print(plr.leaderstats.Level.Value) in the Developer Console it prints out 2 but if I put that code in code it prints out 1.