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

How do I fix this math.random() inside my game.Players.ChildAdded function?

So in the following code, the math.random() only prints out 5 every single time, so here's the code, and thank you for answering in advance.

game.Players.ChildAdded:connect(function(player)
	local color = Instance.new("StringValue")
	color.Name = "TorsoColor"
	color.Parent = player

	local b = math.random(1,5)
	print(b)
	
	if b == 1 then
		color.Value = "Medium stone grey"
	elseif b == 2 then
		color.Value = "Dark Blue"
	elseif b == 3 then
		color.Value = "Maroon"
	elseif b == 4 then
		color.Value = "Earth green"
	elseif b == 5 then
		color.Value = "Brown"
	end	
end)

1 answer

✓ Accepted answer

That's because math.random() is not truly random. You will want to set math.randomseed() to a value that will be new or different each time the function is run. To accomplish this, you can set math.randomseed() to tick().

Tick is defined as:

Returns the number of seconds that have elapsed since the UNIX epoch (January 1st, 1970), on your computer.

Since time is constantly moving forward, tick() will give you a different value every time it is used. Therefore, it is a good value to set as math.randomseed().

It would look like this:

math.randomseed(tick())

You would put this at the beginning of your function, so that is is called prior to math.random().

Below is a link to a Roblox Wiki page regarding random numbers. I highly suggest you read it.

Random numbers

I hope this helps!

If this answer helped you or solved your issue, don't forget to upvote and confirm the answer.

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