MessagingService: total player count 4 instead of 2

Hey! I’m making a total player count system using MessagingService.

Only problem I’ve ran into is that for some reason it says “The total player count is 4” instead of 2.
I’m playTesting this in studio (Test → Local Server with 2 Players)

Here is my code:

local MessagingService = game:GetService("MessagingService")
local Players = game:GetService("Players")

local totalPlayerCount = 0

local function onReceive(msg)
	totalPlayerCount += (msg.Data)
end

Players.PlayerAdded:Connect(function()
	--Subscribe to the topic to portray the amount of players on this server
	MessagingService:SubscribeAsync("PlayerCount", onReceive)
	--Tell all servers that a player joined
	MessagingService:PublishAsync("PlayerCount", 1)
end)

Players.PlayerRemoving:Connect(function()
	--Tell all servers to remove one player
	MessagingService:PublishAsync("PlayerCount", -1)
end)

while true do
	wait(1)
	print("The total player count is " .. tostring(totalPlayerCount))
end

Don’t worry about the while true do loop, this is just for testing, I will definately change it if I implement something like this in a game.
This is a ServerScript in ServerScriptService.

Thanks to a guy from discord I found the solution.
It’s because a listener gets added everytimes a player joins (2 players times 2 listeners = 4).

Here is the working code:

local MessagingService = game:GetService("MessagingService")
local Players = game:GetService("Players")

local totalPlayerCount = 0

local function onReceive(msg)
	totalPlayerCount += (msg.Data)
end

MessagingService:SubscribeAsync("PlayerCount", onReceive)

Players.PlayerAdded:Connect(function()
	--Subscribe to the topic to portray the amount of players on this server
	--Tell all servers that a player joined
	MessagingService:PublishAsync("PlayerCount", 1)
end)

Players.PlayerRemoving:Connect(function()
	--Tell all servers to remove one player
	MessagingService:PublishAsync("PlayerCount", -1)
end)

while true do
	wait(1)
	print("The total player count is " .. tostring(totalPlayerCount))
end
2 Likes