Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

what is the problem with this dataStore script?

I am trying to use a dataStore to save the player's cash but from some reason it does not work, does anyone see what the problem is? (the cash value is stored in an IntValue called "Cash" in leaderstats)

local DataStoreService = game:GetService("DataStoreService")
local cashStore = DataStoreService:GetDataStore("PlayerCash")
local Players = game:GetService("Players")
local AUTOSAVE_INTERVAL = 15
local function saveData(dataStoreKey, value)
	local setSuccess, errorMessage = pcall(function()
		cashStore:SetAsync(dataStoreKey, value)
	end)
	if not setSuccess then
		warn(errorMessage)
	end
end

local function onPlayerRemoving(player)
	local playerUserID = player.UserId
	local playerCash = player.leaderstats.Cash
	if playerCash.Value then
		saveData(playerUserID, playerCash.Value)
		print("cash saved")
	end
end

local function onPlayerAdded(player)
	local playerUserID = player.UserId
	local playerCash = player:WaitForChild("leaderstats"):WaitForChild("Cash")
	local success, storedCash = pcall(function()
		return cashStore:GetAsync(playerUserID)
	end)
	if success then
		local currentCash = storedCash or 100
		playerCash.Value = currentCash
	end

	coroutine.wrap(function()
		while wait(AUTOSAVE_INTERVAL) do
			if playerCash.Value then
				saveData(playerUserID, playerCash.Value)
				print("cash saved")
			end
		end
	end)()
end

Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(onPlayerRemoving)

2 comments

0

Have you tested it outside of studio? And is there any errors in the output?

0

in studio i can just test it with play -> client right? there was an error about sending request to queue but that was fixed when i changed the AUTOSAVE_INTERVAL to 30

3 answers

Maybe try testing this outside of ROBLOX studio, or going to the game settings and turning on API Services for Studio?

If you do not turn on API Services, and test in studio, it won't work.

1 comment

0

I tried testing outside of roblox, i did turn on API Services, still does not work

Hello,

I haven't worked with DataStores in a while but try changing your local playerUserID = player.UserId to local playerUserID = tostring(player.UserId). According to the documentation SetAsync wants a type string. If this is not the case please make sure to comment to I can make it right.

1 comment

0

well i tried it, still does not work

Well turns out the problem was caused because I was changing the cash value from a local script and not the server. the dataStore script itself has no problems. sorry for that I Guess

2 comments

0

why can i not accept this answer?

0

Since it is your own answer, you cannot accept it.

This discussion is preserved as it was. New answers, comments, and votes are closed.