This script is used to keep count how many players are in the server and save that value into a global data store.
However, after some time, it seems to display there are players in a server even when there aren’t.
This means the value is set to 1 or 2 instead of 0.
local ds = game:GetService("DataStoreService")
local data = ds:GetGlobalDataStore("GlobalStore04")
game.Players.PlayerAdded:Connect(function()
local success, err = pcall(function()
data:IncrementAsync("NumberOfPlayersLOW", 1)
end)
if success then
print("Saved")
else
print("Error")
end
end)
game.Players.PlayerRemoving:Connect(function()
local success, err = pcall(function()
data:IncrementAsync("NumberOfPlayersLOW", -1)
end)
if success then
print("Saved")
else
print("Error")
end
local num = data:GetAsync("NumberOfPlayersLOW")
if num == -1 then
data:IncrementAsync("NumberOfPlayersLOW",1)
end
print(num)
end)
The code couldn’t be simpler, it just increments and decrements the value when a player leaves and joins the server.
Is there any way that I could improve this?
Hello, there’s a pretty clear issue with the optimization considering that both these events can be triggered by each and every player accross all servers. The issue you are facing is most likely caused by a ‘race condition’ due to the database operations targetting the same key.
A much better approach you could take is use the PlayerAdded end PlayerRemoving events to store the count on variables and then update the database periodically (every 5 or more minutes).
Aside from that you should add a fair delay after the PlayerAdded event is triggered before considering the player that joined in the count. This will prevent performing unecessary database operations on a player that joined and left in a short period of time.
If you need a code example for a better illustration feel free to ask !
Very bad idea directly writing to the key. Add a delayed write which will have a timer and execute every x.
For the value and figuring out what to write to it you will need to make another variable like plrCount then use that to store the value of players in the server and increment to the value then write that value (plrCount) to the datastore after the delay has been met.
Something you could try is the MessageService and talk between each server from each server to figure out the total player count and not need to write directly to any type of datastore.