Datastore not working! Need help urgent!

Hello! Im making A datastore which saves the donated and recieved value, however it syas its saving and loading but the data is always 0 even if I change the number. I really need help fast. I Cant seem to work out why its not working!

here is the script:

local DataStoreService = game:GetService(“DataStoreService”)

local playerData = DataStoreService:GetDataStore(“PLSSTORE!”)

local function onPlayerJoin(player) – Runs when players join

local playerUserId = “Player_” … player.UserId --Gets player ID

local data = playerData:GetAsync(playerUserId) --Checks if player has stored data

if data then
print(“loaded data for donated and raised”)
local Donated = player.leaderstats.Donated
local Raised = player.leaderstats.Recieved

  Donated.Value = data['Donated']

  Raised.Value = data['Recieved']

else
print(“Notsaving”)
– Data store is working, but no current data for this player

  player.leaderstats.Donated.Value = 0

  player.leaderstats.Recieved.Value = 0

end

end

local function create_table(player)

local player_stats = {}

for _, stat in pairs(player.leaderstats:GetChildren()) do

  player_stats[stat.Name] = stat.Value

end

return player_stats

end

local function onPlayerExit(player) --Runs when players exit

local player_stats = create_table(player)

local success, err = pcall(function()

  local playerUserId = "Player_" .. player.UserId

  playerData:SetAsync(playerUserId, player_stats) --Saves player data

end)

if not success then

  warn('Could not save data!')

end

end

game.Players.PlayerAdded:Connect(onPlayerJoin)

game.Players.PlayerRemoving:Connect(onPlayerExit)

game:BindToClose(function()

for _, player in pairs(game.Players:GetPlayers()) do
local player_stats = create_table(player)

  local success, err = pcall(function()

  	local playerUserId = "Player_" .. player.UserId

  	playerData:SetAsync(playerUserId, player_stats) --Saves player data

  end)



  if not success then

  	warn('Could not save data!')

  end

end

end)

Please help! Thanks!

2 Likes

I tested out the script and it works fine to me. I’m pretty sure you’re just changing the values from client-side, and not from the server, which is why they are not saving.

3 Likes

So first of all, you should use ipairs not pairs.

game:BindToClose(function()

for _, player in ipairs(game.Players:GetPlayers()) do

Second of all use a repeat until for saving the data like this:

        local attempt = 1
		local success = nil
		local err = nil

		repeat
			success, err = pcall(function()

				local playerUserId = "Player_" .. player.UserId

				playerData:SetAsync(playerUserId, player_stats) --Saves player data
				attempt += 1

				if not success then
					warn(err)
				end

			end)
		until success or attempt == 5

2 Likes

Absolute legend thank you! I was just being dumb :slight_smile:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.