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

Choosing a player?

Hello. I tried to pick an "alien" from a table of players. It's not working. The error says:

18:43:22.097 - ServerScriptService.GameScript:15: bad argument #2 to 'random' (interval is empty)

This is my code:

local playerstorage = game:GetService("Players")
local players = {}

while true do

for _, player in pairs(game.Players:GetPlayers()) do
			if player and player.Character then
				local humanoid = player.Character:WaitForChild("Humanoid")
				if humanoid and humanoid.Health > 0 then
					table.insert(players, player)
				end
			end
		end

local alien = players[math.random(1, #players)]

wait(0.1)
end

1 answer

✓ Accepted answer

That just means that the 2nd argument in the math.random function is smaller than the 1st argument. Basically, the script is running when there are no players in the game.

To fix this, simply add a conditional that checks to see if the game has at least 2 players, to prevent errors, like so:

local playerstorage = game:GetService("Players")
local players = {}

while true do
	for _, player in pairs(game.Players:GetPlayers()) do
		if player and player.Character then
			local humanoid = player.Character:WaitForChild("Humanoid")
			if humanoid and humanoid.Health > 0 then
				table.insert(players, player)
			end
		end
	end
	if #players >= 2 then
		local alien = players[math.random(1, #players)]
		--More code
	end
	wait(0.1)
end

Hope this helped!

More info: math.random

2 comments

0

Thanks so much!!!!

0

Only one problem: multiple players are chosen!

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