FenFox
FenFox

Reputation: 117

does Mathf.PerlinNoise() rely on the internal random number generator?

I am using Unity c#, and I am coding something that relies on Perlin noise to determine a random number between 0 and 1. I would like to implement a feature in my code that allows the user to define a specific pre-determined seed number to use for this, but I am not sure if the Perlin noise function actually uses the same random seed as the Random class does.

For example; if I want to generate Perlin noise using Mathf.PerlinNoise() - will it always be the same if I always set the RNG seed priory, using the same number?

minimal code example:

Random.InitState(4815162342);
    float _randomSample = Mathf.PerlinNoise(yada yada yada);

I would like to use this for a Minecraft-like system of generating a procedural game world and having a way for the player to choose a seed would be great. in that code example, the player's chosen seed was the numbers from the TV show "Lost". (4815162342)

Upvotes: 1

Views: 3376

Answers (1)

derHugo
derHugo

Reputation: 90749

The two are not related!

The only thing that Random.InitState changes is the way how e.g. Random.Range or Random.value work.

Without using it it would simply use values based on the system time instead.


Mathf.PerlinNoise is not connected to that. You can actually try different seeds and always see the same perlin result. This is actually stated in the API

The same coordinates will always return the same sample value but the plane is essentially infinite so it is easy to avoid repetition by choosing a random area to sample from.

They already give you a hint how to solve your problem: Use a different offset!

Now here comes your seed into play: Simply choose a random offset based on the seed -> random but always equal for the same seed!

Random.InitState(4815162342);
var randomOffsetX = Random.value;
var rabdomOffsetY = Random.value;

var values = new float[25];
for(var x = 0; x < 5; x++)
{
    for(var y = 0; y < 5; y++) 
    {
        values[x*5 + y] = Mathf.PerlinNoise(x + randomOffsetX, y + randomOffsetY);
    }
}

This should give you 25 random values (between 0 and 1). But they should be equal for every time you use the same seed.


If you actually don't need the noise pattern but only one single value basically you could achieve the same thing simply using

Random.InitState(4815162342);
var value = Random.Range(0f, 1f);

Upvotes: 4

Related Questions