Home > Enterprise >  I do not understand the purpose of this line of code, terrainMap[x, y] = Random.Range(1, 101) < i
I do not understand the purpose of this line of code, terrainMap[x, y] = Random.Range(1, 101) < i

Time:06-26

public void initPos()
{
    for (int x = 0; x < width; x  )
    {
        for (int y = 0; y < height; y  )
        {
            terrainMap[x, y] = Random.Range(1, 101) < iniChance ? 1 : 0;
        }
    }
}

What does below portion of code do? this code is getting used in Unity as part of a script to procedural map generation.

< iniChance ? 1 : 0;

CodePudding user response:

I think you talking about ?: ternary conditional operator

It is the short form of the if else conditions

condition ? statement 1 : statement 2

CodePudding user response:

terrainMap[x, y] = Random.Range(1, 101) < iniChance ? 1 : 0;

is a shorthand expression for

var rndValueBetween1And101 = Random.Range(1, 101);
if (rndValueBetween1And101 < iniChance)
{
   terrainMap[x, y] =  1;
}
else
{
   terrainMap[x, y] =  0;
}
  •  Tags:  
  • c#
  • Related