Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does this still add, even when it's not a player?

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)

2 answers

✓ Accepted answer

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?

This discussion is preserved as it was. New answers, comments, and votes are closed.