Random.new():NextNumber() seems to give the same number every time

Hello!

I’m just wondering how I would go about generating a random Vector3 using Random.new instead of math.random()?

The method I’m using seems to generate 105.38125610351562, 0, 105.38125610351562 every single time. Any ideas of what I’m doing wrong?

local function randomPosition()
	local minX, maxX, minZ, maxZ = 
		baseplate.Position.X - baseplate.Size.X / 2, 
		baseplate.Position.X + baseplate.Size.X / 2, 
		baseplate.Position.Z - baseplate.Size.Z / 2, 
		baseplate.Position.Z + baseplate.Size.Z / 2
	
	local newVector = Vector3.new(
		Random.new(math.random()):NextNumber(minX, maxX),
		baseplate.Position.Y + baseplate.Size.Y / 2,
		Random.new(math.random()):NextNumber(minZ, maxZ)
	)
	print(newVector) --> 105.38125610351562, 0, 105.38125610351562
	return newVector
end

I think it’s because you used a variable for math.random (making it give the same number every time)

Try to do it, without Random.New

You don’t need to put math.random() in the parameter, seeds are generated automatically. I have never used parameterless math.random but it seems to only return one number according to the functionality you described. Remove that and it should work

1 Like

Looks like the seed parameter for Random.new only accepts integer values (unlike what the dev api reference states)

local r1 = Random.new(0)
local r2 = Random.new(0.85725)

print(r1:NextNumber()) --> 0.5514556904749074
print(r2:NextNumber()) --> 0.5514556904749074

You can use an integer range with math.random, e.g. math.random(9e8), or do what dukzae suggested and just remove the seed parameter altogether

1 Like

math.randomseed(tick())

Call it each time you want to generate a new seed.