Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

What is wrong with my dataStores code because it isnt working at all?

I am trying to save some values but it isn't working

local dataStores = game:GetService("DataStoreService") local cashDataStores = dataStores: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.Value = cashDataStores:GetAsync(player.UserId.."_Cash")
Cash.Parent = leaderstats

end)

game.Players.PlayerRemoving:Connect(function(player)

local cashSavingData = player.leaderstats.Cash.Value

cashDataStores:SetAsync(player.UserId.."_Cash", cashSavingData)

end)

2 comments

0

Are you testing in studio? If so, do you have API services enabled

0

What errors if any are you getting in the console?

1 answer

You need to add a bind to close because if there is one player in the game, the game shuts down before the script finishes, a fixed version of your code:

local dataStores = game:GetService("DataStoreService")
local cashDataStores = dataStores: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.Value = cashDataStores:GetAsync(player.UserId.."_Cash")
Cash.Parent = leaderstats
end)

game.Players.PlayerRemoving:Connect(function(player)
local cashSavingData = player.leaderstats.Cash.Value

cashDataStores:SetAsync(player.UserId.."_Cash", cashSavingData)
end)
game:BindToClose:Connect(function()
for _, player in pairs(game.Players:GetPlayers()) do
local cashSavingData = player.leaderstats.Cash.Value

cashDataStores:SetAsync(player.UserId.."_Cash", cashSavingData)
end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.