This script is a datastore for leaderstats. Obviously, its supposed to save, but I doesn't. It worked at first but I changed some things in in and now it doesn't work, whats wrong?
Code:
local dataStoreService = game:GetService("DataStoreService")
local myDataStore = dataStoreService:GetDataStore("MainDataStore")
local playersLeft = 0
-- Load leaderstats
game.Players.PlayerAdded:Connect(function(player)
playersLeft = playersLeft + 1
-- Leaderstats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
-- Coins
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Parent = leaderstats
-- Gems
local gems = Instance.new("IntValue")
gems.Name = "Gems"
gems.Parent = leaderstats
-- Levels
local levels = Instance.new("IntValue")
levels.Name = "Level"
levels.Parent = leaderstats
-- Load data
local PlayerUserId = player.UserId -- Player key to store data
local player_data
-- Data to load in
local dataTable1 = {
Coins = player.leaderstats.Coins.Value;
Gems = player.leaderstats.Gems.Value;
Levels = player.leaderstats.Level.Value;
}
local success, errorMessage = pcall(function()
player_data = myDataStore:GetAsync(PlayerUserId)
end)
-- Load data
if success then
coins.Value = dataTable1.Coins
gems.Value = dataTable1.Gems
levels.Value = dataTable1.Levels
end
end)
local bindableEvent = Instance.new("BindableEvent")
-- Player leaves
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = player.UserId -- Player key
-- Data table
local dataTable2 = {
Coins = player.leaderstats.Coins.Value;
Gems = player.leaderstats.Gems.Value;
Levels = player.leaderstats.Level.Value;
}
local success, errorMessage = pcall(function()
myDataStore:SetAsync(playerUserId, dataTable2)
playersLeft = playersLeft - 1
bindableEvent:Fire()
end)
if success then
print("Data saved")
else
print("Error saving data")
warn(errorMessage)
end
end)
if playersLeft > 0 then
bindableEvent.Event:Wait()
end

1 comment
What is dataTable1 for? Since it's stated before you fetch the data, it will automatically become a zero or nil. Why not just use "player_data.Coins, player_data.Gems", etc etc?