When the player first joins the game, they don't have any value stored in CashDataStore. Therefore, calling CashDataStore:GetAsync(playerUserId) returns nil. Meaning that, at Cash.Value = data.Cash, you're actually saying Cash.Value = nil.Cash. To fix this, you have to check if the datastore is nil and if so, set it to a starter value. That can be done this way:
data = CashDataStore:GetAsync(playerUserId) or {["Cash"] = 0}
When you write variable = value1 or value2, you're setting the value of variable to value1, unless value1 is nil, in which case you set the value to value2.
Testing your script, I also found an error when you try to save everything at this line:
CashDataStore:SetAysnc(playerUserId, data)
The only issue here though is a typo at SetAsync, you wrote SetAysnc. This is easily fixable:
CashDataStore:SetAsync(playerUserId, data)
Here is the new script in its entirety:
local DataStoreService = game:GetService("DataStoreService")
local CashDataStore = DataStoreService:GetDataStore("CashDataStore")
game.Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Cash = Instance.new("IntValue")
Cash.Name = "Cash"
Cash.Parent = leaderstats
local playerUserId = "Player_"..player.UserId
local data
local success, errormessage = pcall(function()
data = CashDataStore:GetAsync(playerUserId) or {["Cash"] = 10}
end)
if success then
Cash.Value = data.Cash
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = "Player_"..player.UserId
local data = {["Cash"] = player.leaderstats.Cash.Value}
local success , errormessage = pcall(function()
CashDataStore:SetAsync(playerUserId, data)
end)
if success then
print("DataSaved")
else
print("An Error Occured Saving Data")
warn(errormessage)
end
end)
However, I do wanna say this; I would heavily discourage you from using PlayerRemoving to save everything as the function is extremely unreliable. Instead, I would recommend you to either save the data every time something changed, like this:
Cash.Changed:Connect(function()
data.Cash = Cash.Value
local success , errormessage = pcall(function()
CashDataStore:SetAsync(playerUserId, data)
end)
end)
or create a loop that saves the date every now and then, like this:
while wait(60) do
data.Cash = Cash.Value
local success , errormessage = pcall(function()
CashDataStore:SetAsync(playerUserId, data)
end)
end
If I missed anything, or you have any further questions, feel free to ask.
1 comment
Why is local data and not local data = something?