I’m writing datastore scripts over and over to try to learn how to write them without continuously looking up tutorials. I noticed the coins don’t save but there isn’t any errors only it saves multiple times (I’m assuming that’s the issue). I followed a tutorial but I never copy pasted and changed variables and names to suit what I wanted to save. Not sure where the problem lies.
---- Datastores and leaderstats ----
---- Variables ----
local runService = game:GetService("RunService")
local dataStore = game:GetService("DataStoreService")
local coinsData = dataStore:GetDataStore("Coins_01")
local function saveData(player) -- function that saves the data
local tableToSave = {
player.leaderstats.Coins.Value, -- first value of the table
player.leaderstats.Rank.Value -- second value of the table
}
-- Save Data --
local success, errorMessage = pcall(function()
coinsData:SetAsync(player.UserId, tableToSave) -- saving the data to player and table we need to save
end)
if success then -- if the data is saved
print("Successfully saved player data!")
else -- if there is an error
print("Data have not been saved!")
warn(errorMessage)
end
end
game.Players.PlayerAdded:Connect(function(player) -- when a player joins the game
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Parent = leaderstats
coins.Value = 0
local rank = Instance.new("StringValue")
rank.Name = "Rank"
rank.Parent = leaderstats
rank.Value = "Noob"
while true do
if player and coins then
coins.Value += 1
task.wait(2)
end
end
-- Load Data --
local data -- data is the table that's saved
local success, errorMessage = pcall(function()
data = coinsData:GetAsync(player.UserId) -- Get the data from the datastore
end)
if success and data then -- if no errors and the player has data
coins.Value = data[1] -- set the coins to the first value of the table (data)
rank.Value = data[2] -- set the rank to the second value of the table (data)
else -- The player didn't load any data, probably a new player
print("The player has no data!") -- Default set to "0"
end
end)
---- When player leaves game ----
game.Players.PlayerRemoving:Connect(function(player)
local success, errorMessage = pcall(function()
saveData(player) -- save the data
end)
if success then
print("Successfully saved player data!")
else
print("Data have not been saved!")
warn(errorMessage)
end
end)
---- When server shuts down ----
if not runService:IsStudio()then
game:BindToClose(function()
for _, player in pairs(game.Players:GetPlayers()) do -- loops through all players
local success, errorMessage = pcall(function()
saveData(player) -- save the data
end)
if success then
print("Successfully saved player data!")
else
print("Data was not saved!")
warn(errorMessage)
end
end
end)
end