How to detect when the amount of players has changed

I am wondering how to run a function whenever the number of players has changed but I couldn’t find any posts on how to do this I have tried things like #players.Changed:Connect(function() but that didn’t work for some reason, someone PLEASE tell me how to do this.

1 Like

You will need to use the game.Players.PlayerAdded: and game.Players.PlayerRemoved events

Heres a basic script:

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

local PlayerAmount : number = 0;

Players.PlayerAdded:Connect(function()
	PlayerAmount = #Players:GetPlayers()
	print(PlayerAmount)
end);

Players.PlayerRemoving:Connect(function()
	PlayerAmount = #Players:GetPlayers()
	print(PlayerAmount)
end);
2 Likes

You can also just check the amount of players in the Players service that have the ClassName “Player” and make a Remote that fires everytime it has changed

Why are you putting in semicolons? There’s no practical use for them in Lua

Is there a problem? The code works perfectly fine, some other programming languages, like python, require you to put semi-colons, they also can work as separators in tables, so they do have a use. It’s just good practice, at least for me.

2 Likes

Don’t use changed if you don’t need too. It checks if the instance its being called on (in this case players) has changed its properties not anything else.

Use actual functions that are supported natively like .PlayerAdded/Removeing.


Code example:

-- put into server script service (sss) if it doesn't work locally.
local players = game:GetService("Players")

local playersTotal: number = #players:GetPlayers() or 0 -- get all players currently inside the game
local oldTotal: number = 0

function Resolve(player: Player)
	
	print(player.Name, "has joined or left.")
	
	oldTotal = playersTotal
	playersTotal = #players:GetPlayers()
	
	print("New total and old total of players:", "\n", "New players: ", tostring(playersTotal), "\n", "Old players: ", tostring(oldTotal))
	
end

players.PlayerAdded:Connect(Resolve)
players.PlayerRemoving:Connect(Resolve)


Output;

 22:44:38.697  thatguybarny1324 has joined.  -  Server - Script:9
  22:44:38.697  New total and old total of players: 
 New players:  1 
 Old players:  0  -  Server - Script:14```

---

Might as well just increment and decrement a number as opposed to counting an array

That’s just pointless when we can get the accurate total of players just by using Roblox’s API without needing any other functions.

How about no functions, no needless memory usage or processing, and no API calls because it’s just as accurate…?