How do I replicate RandomNumberGenerator output with a seed?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Ben Humphries

I’m using a RandomNumberGenerator to help produce a procedurally generated map, and I want its values to be consistent between generations by seeding the RandomNumberGenerator.

From the output it seems to me like the RandomNumberGenerator functions change the seed after each call. For example, the the seed changes after running this line:

		var weight = rng.randf_range(1.0, NOISE_VARIANCE)

Is there a way to prevent the seed from changing so I can save the seed for each map generation?

:bust_in_silhouette: Reply From: jgodfrey

The RandomNumberGenerator object has a seed property that will allow you to provide a seed value. Using that, you should be able to generate a “random”, yet “reproducible”, set of values.

So, for example:

func _ready():
	var rng = RandomNumberGenerator.new()
	rng.seed = 11
	for i in range(4):
		print(rng.randi())

	print("\n")

	rng = RandomNumberGenerator.new()
	rng.seed = 11
	for i in range(4):
		print(rng.randi())

The above creates 2 separate RandomNumberGenerator instances, seeds them both with the same value (11) and then prints their first 4 returned values - which are the same.

So, as long as you feed the object a common seed, you should get the same stream of “random” values. A different seed will change the stream of values…