Search Unity

Random.InitState() generates random numbers but same PerlinNoise map

Discussion in 'Scripting' started by c-Row, Jul 17, 2017.

  1. c-Row

    c-Row

    Joined:
    Nov 10, 2009
    Posts:
    853
    I am slightly stuck on my perlin noise map generation. Whenever I run the script below with different generation seed numbers I get another set of random numbers as expected, but the texture created from the noise map will always look the same.

    Code (csharp):
    1.  
    2.     public Texture2D GenerateTexture(int width, int height)
    3.     {
    4.         Random.InitState(generationSeed);
    5.  
    6.         // sanity testing
    7.         for (int x = 0; x < 5; x++)
    8.         {
    9.             Debug.Log(Random.Range(0f, 1f));
    10.         }
    11.  
    12.      
    13.         Texture2D texture = new Texture2D(width, height);
    14.  
    15.         // generate perlin noise map
    16.         for (int x = 0; x < width; x++)
    17.         {
    18.             for (int y = 0; y < height; y++)
    19.             {
    20.                 float sample = Mathf.PerlinNoise((float)x / (float)width * scale, (float)y / (float)height * scale);
    21.              
    22.                 Color color = new Color(sample, sample, sample);
    23.  
    24.                 texture.SetPixel(x, y, color);
    25.             }
    26.         }
    27.  
    28.         texture.wrapMode = TextureWrapMode.Clamp;
    29.         texture.Apply();
    30.  
    31.         return texture;
    32.     }
    33.  
     
  2. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    I don't see anything in the perlin noise documentation that states the map will be generated based on Random.InitState. In fact, I'm not completely sure the map should be affected by Random.InitState as you want it to be repeatable given the same input values.

    If you wanted a "random map", maybe add a random x,y offset to the x,y parameters instead?

    i.e.
    Mathf.PerlinNoise(x + someRandomOffsetX, y + someRandomOffsetY)
     
    c-Row likes this.
  3. c-Row

    c-Row

    Joined:
    Nov 10, 2009
    Posts:
    853
    Oh, I have always been under the impression (or assumption, probably) that perlin noise was based on a random seed itself, and starting with the same seed would produce the same noise map everytime. Guess random offset is the way to go then.

    Thanks for clearing that up!
     
    assertor likes this.