local Data = game:GetService("DataStoreService"):GetDataStore("tesssst")
game:GetService('Players').PlayerAdded:Connect(function(plr)
local Folder = Instance.new("Folder", plr)
Folder.Name = "Data"
local Cash = Instance.new("IntValue", Folder)
Cash.Name = "Cash"
local Levels = Instance.new("IntValue", Folder)
Levels.Name = "Levels"
local SavedItems = Data:GetAsync(plr.userId)
if SavedItems then
Cash.Value = SavedItems.Cash or 0
Levels.Value = SavedItems.Levels or 0
else
Cash.Value = 0
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local Saving = {["Cash"] = plr:FindFirstChild('Data').Cash.Value,
["Levels"] = plr:FindFirstChild('Data').Levels.Value}
Data:SetAsync(Saving, plr.userId)
end)
Why isn't the datastore saving?
2 answers
This because SetAsync, and other Async methods of DataStoreService, require DataKeys first.
A DataKey, is a custom key that pertains to the User. It needs this key before gathering data as the data is under their account, this key provides confirmation and access to the DataStore.
You gave SetAsync the array to save first, instead of the DataKey, therefore it can’t use it to upload the information for reuse.
Data:SetAsync(Player.UserId, Saving)
Server Script
local DataStore = game:GetService("DataStoreService")
local Data = DataStore:GetDataStore("tesssst")
game.Players.PlayerAdded:Connect(function(plr)
local Folder = Instance.new("Folder", plr)
Folder.Name = "Data"
local Cash = Instance.new("IntValue", Folder)
Cash.Name = "Cash"
Cash.Value = 0
local Levels = Instance.new("IntValue", Folder)
Levels.Name = "Levels"
Levels.Value = 0
local SavedItems = Data:GetAsync(plr.UserId)
if SavedItems then
Cash.Value = SavedItems[1]
Levels.Value = SavedItems[2]
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local Saving = {plr.Data.Cash.Value, plr.Data.Levels.Value}
Data:SetAsync(plr.UserId, Saving)
end)
I revised the script so that its a bit more organized.
There are two problems here, the first is when you tried to save the data, the player's key and data was reversed, so you had a table for a key instead (which cannot occur).
The other issue was that the property "UserId" is capitalized, not lowercase ("userId") as you did.
DataStores also have a tendency to use the nil value for a player even when there is an "or" so its better to state the initial values and later check if the player has any saved data to then alter them.
This discussion is preserved as it was. New answers, comments, and votes are closed.
