# Dynamically creating underwater grass on terrain

Hi Forum,

I have been battling this for several hours now and struggling to find a solution.

I basically have a Terrain object, and I create grass details dynamically at run-time. This is fine, however I want to only create the grass ‘underwater’. By underwater I mean a threshold height (which is determined by my ocean object)

To make things easier for me, by Terrain width and height are 1024 which is exactly the same as the detailWidth and detailHeight.

I can detect when a point is below sea level by using SampleHeight on a point on the Terrain, and comparing if it is below a threshold. In fact I did this in an Update routine to make sure my math worked out fine. The following code (although very slowly), draws some debug lines at all the places that are ‘underwater’ on my Terrain.

``````    void Update () {
TerrainData td = Terrain.activeTerrain.terrainData;
int[,] map = Terrain.activeTerrain.terrainData.GetDetailLayer (0,0, td.detailWidth,td.detailHeight,0);

for(int y = 0; y < td.detailHeight; y++)
{
for(int x = 0; x < td.detailWidth; x++)
{
float wx = x;
float wy = 0;
float wz = y;

Vector3 position = new Vector3(wx,wy,wz);
float height = Terrain.activeTerrain.SampleHeight(position);

float rand = Random.value;
//if ( rand < tolerance )
{

Vector3 start = new Vector3(wx,height,wz);
Vector3 end =  new Vector3(wx,height+1f,wz);
if( height < ocean.transform.position.y )
Debug.DrawLine(   start,end );
}

}

}
``````

Briliant, I slightly adapted the above code to create some grass details. The code is essentially the same.

``````	void CreateGrass(int layer, int amount, float tolerance)
{

TerrainData td = Terrain.activeTerrain.terrainData;
int[,] map = Terrain.activeTerrain.terrainData.GetDetailLayer (0,0, td.detailWidth,td.detailHeight,layer);

for(int y = 0; y < td.detailHeight; y++)
{
for(int x = 0; x < td.detailWidth; x++)
{
float wx = x;
float wy = 0;
float wz = y;

Vector3 position = new Vector3(wx,wy,wz);
float height = Terrain.activeTerrain.SampleHeight(position);

float rand = Random.value;
//if ( rand < tolerance )
{
if( height < ocean.transform.position.y)
map[x,y] = amount;
}

}
}

td.SetDetailLayer(0,0,layer,map);
}
``````

However, when running the game, I see a lot of grass ABOVE the water line. As seen in the following image:

Any ideas how I can fix this? or better yet why would grass appear above the water line even though i’m using the same code as the debug lines and they seem to be fine?

Thanks

It says in the manual that SampleHeight is relative to the terrain position so just check that your terrain’s position is 0 on the world Y axis.