Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Set default value but retain value after that?

Asked by 8 years ago

I've made some code that keeps track of how many users are alive in the game, however, it always resets the alive users to 0 whenever it loops through the code again, so if there's one person in the game and they die, instead of it saying "0 players alive", it will say "-1 players alive", since instead of starting at the number 1 (1 player), it starts at 0.

function GivePlayersValue()
local p = game.Players:GetPlayers()
for i = 1, #p do
local s = Instance.new("StringValue", p[i])
s.Name = "Playing"
end
end

local numberAlive = 0
local stringtoConcat = " PLAYER(S) ALIVE"


function GetAlivePlayers()
local count = 0  --this line is the problem, as it resets the count to 0. I just don't know any alternative
local p = game.Players:GetPlayers()
for i = 1, #p do
if p[i]:FindFirstChild("Playing") then
count = count + 1
else 
count = count - 1
end
end
return count
end

game.Players.PlayerAdded:connect(GivePlayersValue)
while true do
    wait(1)
    local combination = tonumber(GetAlivePlayers())
    for i,v in pairs(game.Players:GetChildren()) do
        v.PlayerGui.PAGui.Count.Text = combination .. stringtoConcat
    end

end

1 answer

Log in to vote
0
Answered by
BlackJPI 2658 Snack Break Moderation Voter Community Moderator
8 years ago

You're problem is that you are trying to count the number of players "playing", but subtract from that count when you encounter a player that isn't "playing".

Think about this: If you were counting the number of apples in a fruit basket, would you subtract one apple from the count if you found an orange? No, just because there is an orange doesn't mean you have to subtract an apple you already counted.

Try changing your GetAlivePlayers function to this:

local function GetAlivePlayers()
    local count = 0
    for _, player in ipairs(game.Players:GetPlayers()) do
        if player:FindFirstChild("Playing") then
            count = count + 1
        end
    end
    return count
end
0
Works perfectly. Thanks! Almorpheus 10 — 8y
0
No problem :) BlackJPI 2658 — 8y
Ad

Answer this question