I have a value names PlayerCount, when a PLAYER joins or leaves I want it to add and subtract the PlayerCount value.
When I look at the PlayerCount value in Play Solo, it is right (PlayerCount.Value == 1). However when I add an object that isn't a PLAYER it still adds it on, EVEN when I have an if v:IsA function.
How to fix this?
local Pc = game.Workspace.Values.PlayerCount function Add() for i, v in pairs(game.Players:GetChildren())do if v:IsA("Player")then Pc.Value = Pc.Value + 1 end end end function Subtract() for i, v in pairs(game.Players:GetChildren())do if v:IsA("Player")then Pc.Value = Pc.Value - 1 end end end game.Players.ChildAdded:connect(Add) game.Players.ChildRemoved:connect(Subtract)
Don't use GetChildren, It doesn't work that well GetPlayers works much better and will reduce the amount of lines needed
local Pc = game.Workspace.Values.PlayerCount function Add() for i, v in pairs(game.Players:GetPlayers()) do Pc.Value = Pc.Value + 1 end end function Subtract() for i, v in pairs(game.Players:GetPlayers()) do Pc.Value = Pc.Value - 1 end end game.Players.PlayerAdded:connect(Add) game.Players.PlayerRemoving:connect(Subtract)
and anywho, you're just trying to get the number of players? You could just do a player added/removing event and do local numplayers = #game.Players:GetPlayers()
Use game.Players:GetPlayers()
to make sure that it only captures Players.
Also, aren't you just meaning to set Pc.Value
to game.Players.NumPlayers
?