Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

I need help making a script that only will be active if more than 1 person is in the game. Any help?

I have a script that randomly chooses 2 players. In this script, if the randomly chosen players are the same, it will re-pick the second player until it is a different player. If there is only 1 player present in the game, however, the script will time out from a loop. I need help fixing this so that the script will not break or timeout.

(Lines 7-10 is the loop that will break the script if 1 player is present in the server.)

Here's the script:

local function choosePlayers()
    local users = game.Players:GetPlayers()
    local user1 = users[math.random(1, #users)]
    local user2 = users[math.random(1, #users)]

    if user1 == user2 then -- the same player might get selected twice.
        while user1 == user2 do 
            -- This loop is entered only if the above is true. 
            user2 = users[math.random(1, #users)]
        end
    end
    return user1, user2 -- return the selected users for convenience 
end

while true do
	wait(3)
	local user1, user2 = choosePlayers()
	print(user1, user2) 
end

1 comment

0

at line 9 do if user1 ~= user2 then break end

1 answer

u can do something like that; where ull have a counter that detects when players join?

local counter = 0
local fired = false

local function choosePlayers()
    local users = game.Players:GetPlayers()
    local user1 = users[math.random(1, #users)]
    local user2 = users[math.random(1, #users)]

    if user1 == user2 then -- the same player might get selected twice.
        while user1 == user2 do 
            -- This loop is entered only if the above is true. 
            user2 = users[math.random(1, #users)]
        end
    end
    return user1, user2 -- return the selected users for convenience 
end

while true do
    wait(3)
    local user1, user2 = choosePlayers()
    print(user1, user2) 
end

game.Players.PlayerAdded:Connect(function()
	counter = counter + 1
	
	if counter => 2 and not fired then fired = true
		choosePlayers() 
	end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.