Im trying to make a datastore for levels so it saves whenever u leave and loads whenever you join. But it just doesnt want to do it. Any fix?
Heres my code so far
local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetDataStore("LevelStorage")
local function saveData(player) -- The functions that saves data
local tableToSave = {
player.leaderstats.Level.Value
}
local success, err = pcall(function()
dataStore:SetAsync(player.UserId, tableToSave) -- Save the data with the player UserId, and the table we wanna save
end)
if success then
print("Data has been saved!")
else
print("Data hasn't been saved!")
warn(err)
end
end
game.Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder", plr)
leaderstats.Name = "leaderstats"
local cash = Instance.new("NumberValue", leaderstats)
cash.Name = "Cash"
cash.Value = 0
local OwnsTycoon = Instance.new("BoolValue", plr)
OwnsTycoon.Name = "OwnsTycoon"
OwnsTycoon.Value = false
local level = Instance.new("IntValue",leaderstats)
level.Name = "Level"
local data
local success, err = pcall(function()
data = dataStore:GetAsync(plr.UserId)
end)
if success and data then
level.Value = data[1]
else
print("The player has no data!")
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, err = pcall(function()
saveData(player)
end)
if success then
print("Data has been saved")
else
print("Data has not been saved!")
end
end)
game:BindToClose(function()
for _, player in pairs(game.Players:GetPlayers()) do
local success, err = pcall(function()
saveData(player)
end)
if success then
print("Data has been saved")
else
print("Data has not been saved!")
end
end
end)