I am really derping out I haven;t scripted in 3 years...
NumPlayers = game.Players.NumPlayers
while true do
if NumPlayers == 2 then
print('It Worked')
end
wait(1)
end
For one thing, please place your code in a code block in the future.
Another, the reason the script is not working is because the variable is the value of the Players Service's NumPlayers at the time it is taken. Meaning whatever number the script got from game.Players.NumPlayers
is the number it will remember. You would be better off placing the game.Players.NumPlayers
in the if then statement.
while true do if game.Players.NumPlayers == 2 then --The script will take NumPlayers from the Players Service directly. print('It Worked') end wait(1) end
Your code could however cause lag if you continue to have while loops in multiple scripts. I would recommend using the .Changed
event for a cleaner code (I tested this script in studio but it would not print if the NumPlayers have changed).
game.Players.Changed:connect(function() --The event fired so the function will handle everything. if game.Players.NumPlayer == 2 then --This will only work if there are two players in game. print('It Worked') end end)
You could use
while wait(1) do --Automatically waits 1 if game.Players.NumPlayers == 2 then print("It Worked!") end end
But if you are wanting to see if the number of players are greater than or equal to 2 players (so that it doesn't only do stuff if there are specifically 2 players) do if game.Players.NumPlayers >= 2 then
Hope this helped
Adding on to the other answers, you could do this:
local ready = false function command() print("It worked!") wait(5) ready = false end while wait() do --wait() is faster than wait(1) if not ready and game:GetService("Players").NumPlayers >= 2 then ready = true --debounce command() end end
This way It won't spam if there is 2 players, it will run if there is 2 or more players, and it will run "command" where you could teleport players.
Hope it helps!