So I am making a game where you have to find the treasure chest and i want a series of random events to happen for example: a random player gets faster
but im trying to get the random player on this script right here
local Players = game:GetService("Players"):GetChildren() game.Players.PlayerAdded:Connect(function(player) wait(0.5) player.CameraMaxZoomDistance = 17 wait(5) local randomplayer = Players[math.random(1, #Players)] randomplayer.Character.Humaniod.WalkSpeed = 30 end)
the other part is for max zoom distance the error is saying 11:32:28.929 ServerScriptService.MaxZoomDistance:8: invalid argument #2 to 'random' (interval is empty) - Server - MaxZoomDistance:8
You need to take a look on math.random()
. It takes interval of numbers (x to y) and chooses random one among them, it needs interval which are numbers between that two numbers. But if first player joins, there is only one player in game.Players
, which means it will be math.random(1,1)
, which is not interval. You got zero numbers between that 2 numbers, that interval is nil, its empty. What is more you defined Players at the top of the script which means it will be zero forever, beecause it wont get updated when player joins!. Here is the solution:
local Players = game:GetService("Players") local numOfPlayers = 0 local function onPlayerAdded(player) numOfPlayers = #Players:GetPlayers() -- get number of players in game player.CameraMaxZoomDistance = 17 local randomPlayer if numOfPlayers > 1 then randomPlayer = Players:GetPlayers()[math.random(1, numOfPlayers)] randomPlayer.Character:WaitForChild("Humanoid").WalkSpeed = 30 end end Players.PlayerAdded:Connect(onPlayerAdded)