Why does this work with 1 but not 60?

I added a time based currency earning system to my game. Everything seems to work out alright, it loads and adds the score and everything’s fine. It saves the score just fine… if it’s 1 per second. I’m sure this has something to do just with limitations that I don’t know because I am smooth brain, so if someone could help and explain what’s going on and how to fix it I’d appreciate it qvq

I have two scripts, this is the DataStore script

local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")


local function onPlayerJoin(player)  -- Runs when players join
	local leaderstats = Instance.new("Folder") 
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local Time = Instance.new("IntValue")
	Time.Name = "Currency"
	Time.Parent = leaderstats



	local playerUserId = "Player_" .. player.UserId
	local data = playerData:GetAsync(playerUserId)
	if data then
		Time.Value = data
	else
		Time.Value = 0
	end
end


local function onPlayerExit(player) 

	local success, err = pcall(function()
		local playerUserId = "Player_" .. player.UserId
		playerData:SetAsync(playerUserId, player.leaderstats.Time.Value) 
	end)
	if not success then
		warn('Could not save data!')	
	end
end

game.Players.PlayerAdded:Connect(onPlayerJoin)

game.Players.PlayerRemoving:Connect(onPlayerExit)

And this is the currency adding script

local function onPlayerJoin(player)

	while true do
		wait(1)
		player.leaderstats.Currency.Value = player.leaderstats.Currency.Value + 1
	end
end

game.Players.PlayerAdded:Connect(onPlayerJoin)

It’s the wait(1) in the second script that breaks it. I change it to 60 and it works just fine in game, it adds the score every minute, but whenever I leave it gives the error that the data didn’t save. It doesn’t if it’s 1, only 60. Why tho.

Please try

if not success then warn(err) end

To know the error that is caused.

1 Like

Try adding a spawn(function(), maybe it doesn’t save because it’s waiting for the wait function to end, though it takes more time for it to end than for you to exit.

Not sure if that will fix it, it’s worth the try though.

local function onPlayerJoin(player)
	spawn(function()
		while true do
			wait(1)
			player.leaderstats.Currency.Value = player.leaderstats.Currency.Value + 1
		end
	end)
end
1 Like