Painting grass on Unity terrain programmability (runtime)

151 views Asked by At

I've been having really bad luck finding information and getting getting a working script to paint grass on terrain programmability,
The most common answer I've found goes along this example:

int[,] newMap = new int[grassDensity, grassDensity];

for (int i = 0; i < grassDensity; i++) {
  for (int j = 0; j < grassDensity; j++) {
    float height = terrain.terrainData.GetHeight(i, j);
    if (height < 1.0f)
    {
      newMap[i, j] = 1;
    } else {
      newMap[i, j] = 0;
    }
  }
}
terrain.terrainData.SetDetailLayer(15, 15, 0, newMap);

But I can't seem to get anything to work, like at all, no results
What currently happens is when a new piece of terrain gets generated as the player walks, It creates a new instance of a ready made GameObject (the chunk in this case), also setting the heights, detail textures, detail layers, etc

Note: the detail textures and detail layers get referenced from a ready made terrain separate to the chunk generation as a attempt to get something working

Want I want is to also 'paint' the detail layer (the grass), it currently doesn't matter about patterns, how often to place the grass, etc. I just want a working way to paint grass on the whole terrain to begin with

I don't know what extra information to add at this point, if you need more information, please tell me

I've tried many examples, I've lost track of them, but it goes along the lines of looping through, setting the int array then putting the array into terrain.terrainData.SetDetailLayer, I've also tried Alphamaps along side it, even trying to copy detail information directly from a test terrain object

1

There are 1 answers

0
SoapierGlobe421 On BEST ANSWER

Edit: After a few experiments, it turns out you need to fill the int array first before looping through it, contrary to other code snippets online So
int[,] newMap = new int[grassDensity, grassDensity];
would be:
int[,] newMap = new int[512, 512]; for a 512x512 Terrain, you could simply use
t.terrainData.detailWidth, t.terrainData.detailHeight,
do note with large int arrays, they can take a long time to create, so if the terrain is 1024x1024, expect it to freeze for awhile