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
local number = 0
game.Players.PlayerAdded:Connect(function(player)
number += 1
end)
game.Players.PlayerRemoving:Connect(function(player)
number -= 1
end)
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)