I'm trying to write a script where every second it saves data =, but it really isn't working :/ Could anyone help?
My script:
local dataStoreService = game:GetService("DataStoreService") local myDataStore = dataStoreService:GetDataStore("myDataStore")
game.Players.PlayerAdded:Connect(function(player)
--- Leaderstats Variables --- Hidden Variables local hiddenVariables = Instance.new("Folder",player) hiddenVariables.Name = "hiddenVariables" local eventsCompleted = Instance.new("IntValue",hiddenVariables) eventsCompleted.Name = "eventsCompleted" while wait(0.1)do local playerUserId = "Player_"..player.UserId local data local success, errorMessage = pcall(function() data = myDataStore:GetAsync(playerUserId) end) if success then eventsCompleted.Value = data end end
end)
Do u have API services on? Thats a setting that MUST be turned on for things to save.
The main issue that I see is that you are using :GetAsync()
. :GetAsync()
is used for getting data from the datastore. When the player leaves the game you should use :SetAsync()
in order to save their data after they've left.
Fixed script:
local dataStoreService = game:GetService("DataStoreService") local myDataStore = dataStoreService:GetDataStore("myDataStore") local function encodeUserId(player) return "Player_" .. player.UserId end game.Players.PlayerAdded:Connect(function(player) --- Leaderstats Variables --- Hidden Variables local hiddenVariables = Instance.new("Folder", player) hiddenVariables.Name = "hiddenVariables" local eventsCompleted = Instance.new("IntValue",hiddenVariables) eventsCompleted.Name = "eventsCompleted" local playerUserId = encodeUserId(player) local success, errorMessage; while not success do local data success, errorMessage = pcall(function() data = myDataStore:GetAsync(playerUserId) end) if success then eventsCompleted.Value = data else warn(errorMessage) wait(2) end end end) game.Players.PlayerRemoving:Connect(function(player) local playerUserId = encodeUserId(player) local success, errorMessage; while not success do local success, errorMessage = pcall(function() myDataStore:SetAsync(playerUserId, player.hiddenVariables.eventsCompleted.Value) end) if not success then warn(errorMessage) wait(2) end end end)
It also appears that you have only copied part of your script so I cannot guarantee that this will all work.