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

Code using GetPlayers simply not working?

Asked by 4 years ago

I made some code that's supposed to get the number of players in the game and determine what level of the game the players will be in by that number. Its parent is a textlabel, so the text is supposed to change judging by the number of players as well. For some reason, it doesn't do anything at all. There's no errors in the console, just nothing happens at all. I put in some prints to see where it stops working, and it only gets as far as 1. Is there something I'm doing blatantly wrong? Sorry if this is stupid

local text = script.Parent.Text
local gameStage = nil --gamestage is which level of the arena they're on. if players = 20-9, 1. 8-5, 2. 4-2, 3.
local timer = nil

print("1")

function StartGame(players)
    print(players)
    timer = 10
    repeat
        text = timer
        wait(1)
        timer = timer - 1
    until timer <= 0
end
game.Players.PlayerAdded:Connect(function()
    print("2")
    for num,v in pairs(game.Players:GetChildren()) do
        print("3")
        if num < 2 then
            text = "Waiting for players"
            print("4")
        elseif (num >= 2 and num <= 4) then --players 2-4
            gameStage = 3
            StartGame(num)
            print("4")
        elseif (num >= 5 and num <= 8) then --players 5-8
            gameStage = 2
            StartGame(num)
            print("4")
        elseif (num >= 17 and num <= 20) then --players 9-20
            gameStage = 1
            StartGame(num)
            print("4")
        end
    end
end)

1 answer

Log in to vote
0
Answered by
sleazel 1287 Moderation Voter
4 years ago
Edited 4 years ago

You have two issues. Quote:

Its parent is a textlabel

You are not referencing TextLabel, you have just copied text into the variable. Proper way to do it is:

text = script.Parent
--and later in the script
text.Text = timer

To get number of players

Now the more serious problem. Your script is parented to the text label. If its a TextLabel on PlayerGui it needs to be a LocalScript. While it will work, it will only run after another player joins the game and it will not run for current player and players that joined before. Furthermore for old players it will run multiple times. You will need to use remote event for PlayerGui, and run the code on server in server script.

On the other hand if your script is parented to the textlabel in the workspace surface or billboard gui it will still run multiple times each time new player joins.

Have a nice scripting session.

EDIT: Also that loop is not needed and actually will probably not work as intended:

for num,v in pairs(game.Players:GetChildren()) do
--use this instead
num = #game.Players:GetChildren()
Ad

Answer this question