Leaderstats keeps disappearing

local DataStore2 = require(1936396537)

DataStore2.Combine("MasterKey", "Level", "XP")
local DS = game:GetService("DataStoreService"):GetDataStore("0x2e9_0x4")

local Default_Level = 1
local Default_XP = 0

local xpToLevelUP = function(level)
	return 100 + level * 5
end

game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = plr
	
	local Level  = Instance.new("IntValue")
	Level.Name = "Level"
	Level.Parent = leaderstats
	
	local XP = Instance.new("IntValue")
	XP.Name = "XP"
	XP.Parent = leaderstats
	
	
	--DATA STORE--
	local Level_Data = DataStore2("Level", plr)
	local XP_Data = DataStore2("XP", plr)
	
	--FUNCTIONS--
	local function updateLevel(level)
		plr.leaderstats.Level.Value = level
	end
	
	local function updateXP(XP)
		if XP >= xpToLevelUP(Level_Data:Get(Default_Level)) then
			XP_Data:Increment(xpToLevelUP(Level_Data:Get(Default_Level)) * -1)
			Level_Data:Increment(1)
		else
			plr.leaderstats.XP.Value = XP
		end
	end
	
	updateLevel(Level_Data:Get(Default_Level))
	updateXP(XP_Data:Get(Default_XP))
	
	Level_Data:OnUpdate(updateLevel)
	XP_Data:OnUpdate(updateXP)
	
end)

This script is inside SSS (Normal script)
So sometimes leaderstats shows and sometimes it doesnt (in studio)

Perhaps the player is joining before the PlayerAdded event code is ready to be fired upon. Try this:

local Players = game:GetService("Players")

local function PlayerAdded(player)
    -- player added code here
end

Players.PlayerAdded:Connect(PlayerAdded)

for _, player in ipairs(Players:GetPlayers()) do
    coroutine.wrap(PlayerAdded)(player)
end
1 Like

No, that’s not the problem… Roblox Studio has been having bugs, i’ve been experiencing this aswell. The thing that helped me is inserting a model of mine into workspace which makes the leaderstats appear all the time.

1 Like

plain confusion why you need 2 datastores

:laugh:, if you put the loop under the playeradded event, there’s a chance it can be fired twice

I’ve been experiencing this as well and this fixed it for me completely.

This really wouldn’t matter depending on how your code execution functions.

1 Like