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

Is it possible to create global counters?

Is it possible to create a global counter so a counter with the same number on all servers (This counter is to show how many minigames have been loaded in total)

What i have:

local key = 1234
local ds = game:GetService("DataStoreService"):GetDataStore("Test")


function UpdateValue()
if ds:GetAsync(key) then
ds:SetAsync(key, ds:GetAsync(key) + 1)
end
end

--this part is just for testing--
wait ()
while true do
    wait (1)
    UpdateValue()
end

for some reason this script doesnt work

1 answer

DataStores require a key in which it will save data under. For this case, we can use the game's Id to save the amount of rounds had gone by.

We're also going to try to get away from any possible DataStore limits by saving the rounds after the server closes.

--Define DataStore service and get out RoundCount data.
--If no DataStore is called RoundCount then this will create one
local DS = game:GetService("DataStoreService")
local RoundCountStore = DS:GetDataStore("RoundCount")

--We will keep this as a global variable that we increment in the loop
--We then save it if the game closes
local roundsPassed = 0

--BindToClose fires if the server closes down.
game:BindToClose(function()
	if roundsPassed > 0 then
		--Using IncrementAsync to save the amount of rounds passed
		RoundCountStore:IncrementAsync(game.GameId, roundsPassed)
	end
end)

--Basic while loop  that increases roundsPassed variable by 1
while true do
	roundsPassed = roundsPassed + 1
	print("Rounds passed: "..roundsPassed)
	
	wait(5)
end

This is the way I would go about handling non-player data but I also never use DataStoreService directly. I currently use community-made module DataStore2 for my saving needs since I don't like dealing with data limits and data failing to save.

If anyone sees anything wrong with this let me know.

1 comment

0

When I quit the test, it pops up: Not running script because past shutdown deadline (x263)

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