- Home /
Placing grass on terrain in script on a certain height
I'd like my grass to be placed only on certain heights of the terrain (so grass wouldn't be placed underwater or high up in the mountains). I know there is a way to do this, I just can't really wrap my head around on how to edit the grass. Could anyone help me out here? Here is my code which places grass all over the terrain.
void Start()
{
terrainToPopulate = transform.gameObject.GetComponent<Terrain>();
terrainToPopulate.terrainData.SetDetailResolution(grassDensity, patchDetail);
int[,] newMap = new int[grassDensity, grassDensity];
for (int i = 0; i < grassDensity; i++)
{
for (int j = 0; j < grassDensity; j++)
{
newMap[i, j] = 6;
}
}
terrainToPopulate.terrainData.SetDetailLayer(0, 0, 0, newMap);
}
Thank you in advance.
Answer by Winterblood · Feb 13, 2016 at 08:19 PM
Try this, then customise the height/density rules as you need them:
void Start()
{
terrainToPopulate = transform.gameObject.GetComponent<Terrain>();
terrainToPopulate.terrainData.SetDetailResolution(grassDensity, patchDetail);
int[,] newMap = new int[grassDensity, grassDensity];
for (int i = 0; i < grassDensity; i++)
{
for (int j = 0; j < grassDensity; j++)
{
// Sample the height at this location (note GetHeight expects int coordinates corresponding to locations in the heightmap array)
float height = terrainToPopulate.terrainData.GetHeight( i, j );
if (height < 10.0f)
{
newMap[i, j] = 6;
}
else
{
newMap[i, j] = 0;
}
}
}
terrainToPopulate.terrainData.SetDetailLayer(0, 0, 0, newMap);
}
Thank you, it worked when I switched .GetHeight( i, j ); to .GetHeight( j, i );.
Answer by manyokibenc · Feb 14, 2016 at 05:51 PM
Hello, my grass creator script works by checking the terrain's texture data, and places grass only to specific textures, so you should use Terrain Toolkit to apply textures by height, and use a code like mine to generate the grass. I will put my script to asset store, so if you are interested please contact me! Cheers B.
Your answer
Follow this Question
Related Questions
Save terrain grass data 0 Answers
Gras Dissapears in build 1 Answer
Terrain heightmap isn't smooth 0 Answers
Unity terrain grass extremely weird 0 Answers
Plant grass or tree with an image 0 Answers