Is there a way to detect if someone leaves/joins within one function?

I know that you can do game.Players.Playeradded to detect when someone joins
and I also know that you can do game.Players.PlayerRemoving to detect when someone leaves

but is there a way to detect whenever someone leaves/joins within one function?
I’m trying to figure this out for a player counter I have
It updates when someone joins but the number doesn’t go down because there’s nothing to tell it to
image

2 Likes

You could just connect PlayerAdded and PlayerRemoving to the same function?

Something like this:

local function foo(player)

-- blah blah blah

end

game.Players.PlayerAdded:Connect(foo)

game.Players.PlayerRemoving:Connect(foo)
2 Likes

is there a way to do this in the way I format my functions?

1 Like

That would be pretty useless


What exactly is the problem? Just connect a PlayerRemoving event and change the “count” variable

local number = 0

game.Players.PlayerAdded:Connect(function(player)
     number += 1    
end)

game.Players.PlayerRemoving:Connect(function(player)
     number -= 1
end)
1 Like

Unfortunately not that I know of.

Alright, I made this script real fast, tell me if there is a error:

local gui = script.Parent
local children = game:GetService("Players"):GetChildren()
local plr = game:GetService("Players") -- add a .LocalPlayer if it's a local script


local count = #children

local function pro(number)
if plr then
count += number
gui.Text = count
elseif not plr then
count -= number
gui.Text = count
end

game.Players.PlayerAdded:Connect(pro,1)

game.Players.PlayerRemoved:Connect(pro, 1)

Firstly that script would not work (and doesn’t make sense)

Secondly that’s overly complicated.

You should follow the Single-Responsibility-Principle and have each function do one thing (avoid boolean parameters that change functionality)

-- server script
local player_count = 0

game.Players.PlayerAdded:Connect(function(player)
     player_count += 1
     -- you can update players ui via remote or something here
end)

game.Players.PlayerRemoving:Connect(function(player)
     player_count -= 1
     -- you can update players ui via remote something here
end)

I don’t know maybe something like this :


--Server Script

local RE = Instance.new("RemoteEvent")
RE.Name = "PlayerCount"
RE.Parent = game.ReplicatedStorage

local playerLeft = 0
game.Players.PlayerAdded:Connect(function(player)
	playerLeft = playerLeft + 1
	RE:FireAllClients(playerLeft)
end)
game.Players.PlayerRemoving:Connect(function(player)
	playerLeft = playerLeft - 1
	RE:FireAllClients(playerLeft)
end)

--Client Script
wait(3)
local gui = script.Parent
local RE = game.ReplicatedStorage.PlayerCount
RE.OnClientEvent:Connect(function(count)
	gui.Text = count
end)


you guys all overcomplicated this, this is as simple as the an answer that I needed
I didn’t need feedback on how terrible a newbies scripting may be

1 Like