Failure to select player using math.random

Hello there! I’ve created a module to select a random Killer and give that Killer a sword, as well as teleport players to the map’s teleport part, yet the selecting a Killer doesn’t work, meaning giving them a sword won’t work, of course!

Here’s the module script:

local module = {}

function module.ChooseKiller()
	local Killer = game.Players:GetPlayers()[math.random(1, #game.Players:GetPlayers())]
	local WoodenSword = game.ServerStorage.WoodenSword
	WoodenSword:Clone().Parent = Killer.Backpack
	print(Killer.Name)
end

function module.TeleportPlayers()
	for i,v in pairs(game.Players:GetPlayers()) do
		local Character = v.Character
		if Character then
			Character.HumanoidRootPart.CFrame = workspace.Map.TeleportPart.CFrame
		end
	end
end

return module

The print returns “nil”
image

Anybody have any idea as to why this happens? Let me know!

hey, can you send the code that starts function module.ChooseKiller()? thanks

it could be because the game started before the player could officially join but i’m not sure because you only sent in your module script

This is all that’s in it for now:

local Module = require(script:WaitForChild("Functions"))

function StartRound()
	wait(5)
	Module.ChooseKiller()
	wait(3)
	Module.TeleportPlayers()
end
wait(1)
StartRound()

you could create a function using PlayerAdded (for testing purposes) to connect the StartRound() function

here’s an example

local Module = require(script:WaitForChild("Functions"))

function StartRound()
      wait(5)
      Module.ChooseKiller()
      wait(3)
      Module.TeleportPlayers()
end

game.Players.PlayerAdded:Connect(StartRound) -- this will fire each time a player joins so maybe add a cooldown or indicator to check if the game has started or not

I’ll give it a go! You’re completely right, about how the game could be starting before the player actually finishes joining up! :smile:

1 Like

Additionally, it is recommended that you use the Random object over math.random because it is “more random”.

EDIT: This is actually not true- just checked. Forgot they updated math.random to be just as reliable as the Random object.

i have never heard of that before lol, i usually just use the same thing as OP, which is just using math.random() to randomly pick an index in an array

edit: V oh cool, didn’t know that before lol

I was mistaken. About a year ago it was the case that the Random object was superior. math.random has since been updated to use the same formula. However; the Random object guarantees fairness so it still has some advantages. Because it creates an object the pseudorandom numbers have not been messed with and will be local - whereas math.random is a global random.

3 Likes