Better way to check how many players playing than datastore?

I’ve been working on a project where there are many tracks for players to head to drive at. The tracks are selected at a main menu screen.

Currently I’m using DataStores to add & subtract number of players online each place, however I find sometimes the subtract fails to run and thus I get incorrect “Players Online:” at the menu. I was concerned maybe the PlayerRemoving function wasn’t running, so I opted to include a BindToClose as well but that still hasn’t remedied the issue.

local datastore = game:GetService("DataStoreService")
local gamedata = datastore:GetDataStore("TrackName")

game:BindToClose(function()	
	local curPlrs = gamedata:GetAsync("OnlinePlayers")
	local plrs = game.Players:GetPlayers()
	local numPlrs = #plrs
	local updatedPlrs = curPlrs - numPlrs
	if updatedPlrs < 0 then
		updatedPlrs = 0
	end
	gamedata:SetAsync("OnlinePlayers", updatedPlrs)
end)

game.Players.PlayerAdded:connect(function(player)
	gamedata:IncrementAsync("OnlinePlayers", 1)
end)

game.Players.PlayerRemoving:connect(function(player)
	gamedata:IncrementAsync("OnlinePlayers", -1)
end)

Is there a better solution than datastores? Is it something particular poor in my code?

1 Like

You should try using :UpdateAsync instead of :SetAsync() to prevent data loss.