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

Why is this script that is supposed to detect if a value changes not working?

Asked by 9 years ago

The script is supposed to detect if at first if there is at least one person on each team. If there is, it will print a message saying "Game can begin", and if there is not at least one person on each team, it will print a message saying "Game cannot begin."

I want it to check if the amount of players on each team has changed, and if so, I want it to react if the amount of players on each team becomes at least one when it was originally 0, and vice versa.

However, I added a line to the code, and it seems once it gets to this point, it is not working. Output gave me feedback, which I will post after the code. Can someone please help me? Here's the script:

local team = game.Teams;

function getPlayers(teamColor) -- team color is easier than name
    local found = { };
    for _,v in pairs(game.Players:GetPlayers()) do
        if v.TeamColor == teamColor then
            table.insert(found, v)
        end
    end
    return #found
end

while wait() do
local greenNum = getPlayers(BrickColor.new('Bright green'))
local redNum = getPlayers(BrickColor.new('Bright red'))
greenNum.Changed:connect(function()
if greenNum > 0 and redNum > 0 then
    print('Game can begin')
elseif greenNum == 0 or redNum == 0 then
    print('Game cannot begin')
end
end)
end

Output: attempt to index local 'greenNum' (a number value)

1 answer

Log in to vote
0
Answered by
Aethex 256 Moderation Voter
9 years ago

The output provided is just telling you that line 16 is not valid code. What you wrote would literally translate to 3.Changed:connect(function() if greenNum was three. The changed event would also not work on a variable defined by the user, but it is also completely unnecessary with the while loop you have running.

All you would have to do is run the if statement every time the while loop runs based on your code:

local team = game.Teams;

function getPlayers(teamColor) -- team color is easier than name
    local found = { };
    for _,v in pairs(game.Players:GetPlayers()) do
        if v.TeamColor == teamColor then
            table.insert(found, v)
        end
    end
    return #found
end

while wait() do
    local greenNum = getPlayers(BrickColor.new('Bright green'))
    local redNum = getPlayers(BrickColor.new('Bright red'))
    if greenNum > 0 and redNum > 0 then
        print('Game can begin')
    elseif greenNum == 0 or redNum == 0 then
        print('Game cannot begin')
    end
end

There would honestly be no reason to use the Changed event, even if it did work in the way you attempted.

Ad

Answer this question