So I am a beginner attempted to do something that is definitely a tad bit more advanced than anything I have scripted previously.
I’m following along with a tutorial on how to create my own Data Stores and have user’s in-game “cash” save.
I’m not getting are error messages on the console but when I join the game, set my cash value and then leave and rejoin a new server, my cash amount is not saving.
Here is the code not sure what I am doing wrong:
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 = "Cash"
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 a critical error while retrieving your data")
warn(errormessage)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local success, errormessage = pcall(function()
myDataStore:SetAsync(player.UserID.."-cash",player.leaderstats.Cash.Value)
end)
if success then
print("Play Data successfully saved!")
else
print("There was an error when saving data")
warn(errormessage)
end
end)
Maybe use game:BindToClose:Connect(function() to save the players data on server shutdown. I see no flaw in your code besides some bad practices and stuff that could be changed but I don’t want to stress you out since your a beginner. Also try playing the game out of studio.
Try to use a tostring after the Async and make BindToClose event
Try this
local RunService = game:GetService("RunService")
game:BindToClose(function()
if not RunService:IsStudio() then
local players = game.Players:GetPlayers()
for _, player in pairs(players) do
player:Kick("Server is shutting down: Please rejoin, your data will be saved.")
end
while true do
wait()
end
else
wait(5)
end
end)
Just re-looked at your code and in the PlayerRemoving event, when you are saving it with a key, the key is player.UserID. A player instance does not have a UserID property but it has a UserId property. Try making the D lowercase.