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 playerUserId = "Player_"..player.UserId
-- Load Data
local data
local success, errormessage = pcall(function()
data = myDataStore:GetAsync(playerUserId)
end)
if success then
Cash.Value = data
-- Set our data equal to the current Cash
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = "Player_"..player.UserId
local data = player.leaderstats.Cash.Value
local success, erromessage = pcall(function()
myDataStore:SetAsync(playerUserId, data)
end)
if success then
print("Data saved successfully!")
else
print("There was an error!")
warn(erromessage)
end
end)
COMMUNITY QUESTION
I Tried out Datastores, and tried to save a value for a player to the server and nothing happened?
1 answer
The problem is that when the last player in the game leave, the server will shut down immediately and this also happens the same when you shut down the server with players still in the game so you would need to make sure that their data is save. So what you should do is just add this code:
game:BindToClose(function()
repeat
local player = game.Players:GetChildren()
wait(1)
until #player = 0
end)
Hope this help!
This discussion is preserved as it was. New answers, comments, and votes are closed.
