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

Help With Player Detection?

Asked by
Scootakip 299 Moderation Voter
8 years ago
local NumPlayers = #game.Players:GetPlayers();
if NumPlayers > 1 then
--- script here
else
print("Not enough players")
end

This part of the script is basically made to not let the rest of the script run unless there's more than 1 player in the game. However, no matter what it always just says that there's not enough players, even with 2 players in the game. Help?

0
If any of these answers help you, mind accepting them so people know the problem's been solved? AwsomeSpongebob 350 — 8y

2 answers

Log in to vote
-1
Answered by 8 years ago

What it looks like to me is that your running the function once, immediately when the first player joins. Assuming your doing this, that's your problem. The script runs before/while the second player connects. What you'll need to do is call the function when a new player joins, perhaps like this?

game.Players.OnPlayerAdded:connect(function(player)
    local NumPlayers = #game.Players:GetPlayers();
    if NumPlayers > 1 then
    --- script here
    else
    print("Not enough players")
    end
end)

Of course, that just a suggestion, you should do it however you see fit.

Also, notice how I define the number of players in the 'OnPlayerAdded' function, and not outside of it. This way, the game can check the number of players each time a new one joins. Of course, it wont run/check how many there are if a player leaves, but you can fix that if need be. Hope this helps! :)

Ad
Log in to vote
0
Answered by
Wutras 294 Moderation Voter
8 years ago
local NumPlayers = #game.Players:GetPlayers();
if NumPlayers > 1 then
--- script here
else
print("Not enough players")
end

That's some mean problem that I ran into several times already too. This only checks ONCE if there are enough players. It is supposed to check until the needed amount is reached. So just do it like that:

local NumPlayers = #game.Players:GetPlayers();
repeat
    if NumPlayers > 1 then
        -- script here
    else
        print("Not enough players")
    end
    wait()
until NumPlayers > 1

repeat wait() until is a kind of loop that is supposed to happen until something has happened. Now if it's about the variable itself, you may also try a few other methods. Like table.getn() or even a for loop. table.getn() gets the length of a table, so you could do it like that:

local NumPlayers = table.getn(game.Players:GetPlayers())
repeat
    if NumPlayers > 1 then
        -- script here
    else
        print("Not enough players")
    end
    wait()
until NumPlayers > 1

Hope this helps!

0
Why repeat? You could just use a OnPlayerAdded Event to trigger the function. AwsomeSpongebob 350 — 8y
0
The repeat will make the script run only once, the event will make it run whenever there was a player added. Wutras 294 — 8y

Answer this question