What I’m trying to create here is a simple script that displays a message when there is an insufficient number of players on the server and organizes a round whenever there are more than two players on at once.
This, however, does not seem to work for some reason. The first part of the script where it checks for one or less players on the server works just fine, though it seems to go downhill from there; continuing on with the statement even after another player joins.
I’ve had no errors in the output thus far and I’m not really sure what the issue is - any help would be appreciated.
Here is a simplified version of the script:
local Players = game:GetService("Players")
local RoundPlayers = Players:GetPlayers()
while true do
while #RoundPlayers <= 1 do
print("One.")
wait(4)
end
if #RoundPlayers >= 2 then
print("Two.")
wait(5)
end
end
I experienced the same issues with this simplified script as I do with the full one, so it can’t have anything to do with that. Again, any help would be much appreciated: thanks!
To get it to work as you intend, there are a couple ways of doing this:
Using :GetPlayers() inside the loop.
local Players = game:GetService("Players")
local RoundPlayers = Players:GetPlayers()
while true do
while #RoundPlayers <= 1 do
print("One.")
wait(4)
RoundPlayers = Players:GetPlayers()
end
if #RoundPlayers >= 2 then
print("Two.")
wait(5)
RoundPlayers = Players:GetPlayers()
end
end
Using PlayerAdded outside the loop and updating a variable that the loop can reference.
local Players = game:GetService("Players")
local RoundPlayers = Players:GetPlayers()
local function updatePlayerCount()
RoundPlayers = Players:GetPlayers()
end
Players.PlayerAdded:Connect(updatePlayerCount)
Players.PlayerRemoving:Connect(updatePlayerCount)
while true do
while #RoundPlayers <= 1 do
print("One.")
wait(4)
end
if #RoundPlayers >= 2 then
print("Two.")
wait(5)
end
end
local Players = game:GetService("Players")
local RoundPlayers = Players:GetPlayers()
local function updatePlayerCount()
RoundPlayers = Players:GetPlayers()
end
Players.PlayerAdded:Connect(updatePlayerCount)
Players.PlayerRemoving:Connect(updatePlayerCount)
while task.wait() do
if #RoundPlayers <= 1 then
print("One.")
task.wait(1)
elseif #RoundPlayers >= 2 then
print("Two.")
task.wait(1)
end
end
There’s no point in having a while loop nested inside of another while loop, a single conditional statement will suffice, to add onto the previous statement, a single conditional chain which uses elseif would be better (as you’d skip checking the 2nd statement if the 1st resolves as true), replace wait() with task.wait() for accuracy and finally perhaps consider reducing the delay from 5 seconds to 1 second.