Need help for Data store system

I want to make a stats save system however whenever i leave it doesnt save

Code:

game:IsLoaded(function()
local DataStoreService = game:GetService(“DataStoreService”)
local dataStore = DataStoreService:GetDataStore(“MyDataStore”)
local function saveData(player)
local valuestosave = {
player.leaderstats.Level,
player.PlayerValueFolder.Exp,
player.PlayerValueFolder.Tokens
}
local success, err = pcall(function()
dataStore:SetAsync(player.UserId, valuestosave)
end)

	if success then
		print("data has been saved")
	else
		print("not")
		warn(err)
	end
end

game.Players.PlayerAdded:Connect(function(player)
	
	local level = player.leaderstats.Level
	local Exp = player.PlayerValueFolder.Exp
	local Tokens = player.PlayerValueFolder.Tokens
	
	local data
	
	local success, err = pcall(function()
		data = dataStore:GetAsync(player.UserId)
	end)
	if success then
		level.Value = data[1]
		Exp.Value = data[2]
		Tokens.Value = data[3]
		
	else
		print("no data")
	end
end)

game:BindToClose(function() -- When the server shuts down
	for _, player in pairs(game.Players:GetPlayers()) do -- Loop through all the players
		local success, err  = pcall(function()
			saveData(player) -- Save the data
		end)

		if success then
			print("Data has been saved")
		else
			print("Data has not been saved!")
		end
	end
end)
end)

This is my first time posting here btw so any tips would be appreciated!<3
And yes,I did double check the values that are going to be saved.

You don’t need this, and it’s not correct either way.

game.Loaded:Wait() 
or
game.Loaded:Connect(function()
or 
repeat wait() until game.IsLoaded -- not recommended
1 Like

Plus, it should be in ReplicatedFirst if you are waiting for the game to load. Don’t worry about loading…

1 Like