SO as the title stated my currency script has a data store in it, but for some reason the data is not saving, so when I leave and join the game the data somehow vanishes. Please help me.
local DataStoreService = game:GetService("DataStoreService")
local PlayerCash = DataStoreService:GetDataStore("PlayerCash")
function OnPlayerAdded(player)
local stats = Instance.new("Folder", player)
stats.Name = 'leaderstats'
local Cash = Instance.new("NumberValue", stats)
Cash.Name = "Coins"
Cash.Value = 0
local data
local success, err = pcall(function()
data = PlayerCash:GetAsync(player.UserId)
Cash.Value = data or 0 -- default
end)
if success then
print("Data loaded!")
else
print("There was an error While Getting Data" ..player.Name)
warn(err)
end
end
function OnPlayerRemoving(player)
local success, err = pcall(function()
PlayerCash:SetAsync(player.UserId, player.leaderstats:FindFirstChild("Cash").Value)
end)
if success then
print("Data Saved!")
else
print("There was an error while saving data of player " .. player.Name)
warn(err)
end
end
game.Players.PlayerAdded:Connect(OnPlayerAdded)
game.Players.PlayerRemoving:Connect(OnPlayerRemoving)
Wait Okay I might have figured it out, but this isn’t working, I scrapped the old script and made a new one.
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local cash = Instance.new("IntValue")
cash.Name = "Coins"
cash.Parent = leaderstats
local data
local success, errormessage = pcall(function()
data = myDataStore:GetAsync(player.UserId.."-cash")
end)
if success then
cash.Value = data
else
print("There was an error whilst getting your data")
warn(errormessage)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall(function()
myDataStore:SetAsync(player.UserId.."-coins",player.leaderstats.Coins.Value)
end)
if success then
print("Player Data succesfully saved")
else
print("There was an error when saving Data")
warn(errormessage)
end
end)
You’re trying to set player.UserId…"-coins" to the value when the player leaves, but you’re trying to get player.UserId…"-cash" when the player joins.
if success then
cash.Value = data
else
print("There was an error whilst getting your data")
warn(errormessage)
end
You should make it this.
if success and data ~= nil then --If they have played the game before
cash.Value = data
elseif success and data == nil then --If they are new, and should get the starting amount
cash.Value = 0
end
So I did what you told me, can you tell me why this isn’t working…
if success and data ~= nil then --If they have played the game before
cash.Value = data
else
if success and data == nil then --If they are new, and should get the starting amount
cash.Value = 0
end