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.

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);
}

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.