[Unity] Removing grass grown on Terrain from scripts


I’ve been testing the need to be able to partially erase the grass that grows on terrain in the zombie content I’m working on.

First, I placed a transparent cube in the field and set the collider to “is trigger”.

Place the cube in the appropriate position so that it overlaps the grassy area in TERRAIN.

Next, create a new script and attach it to the cube. The script is named appropriately.

Below is the code to erase the grass in the area that is in contact with the cube.

.
    public float grassClearRadius = 5f;
    public int detailLayer = 0;

    private Terrain terrain;.

    void Start()
    {
        terrain = Terrain.activeTerrain;



        TerrainData runtimeData = Instantiate(terrain.terrainData);
        terrain.terrainData = runtimeData;


    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject == terrain.gameObject)
        {
            ClearGrass(transform.position, grassClearRadius);
        }
    }

    void ClearGrass(Vector3 pos, float radius)
    {
        if (terrain == null) return;

        TerrainData data = terrain.terrainData;
        int detailResolution = data.detailResolution;

        Vector3 terrainPos = pos - terrain.transform.position;
        int centerX = (int)(terrainPos.x / data.size.x * detailResolution);
        int centerY = (int)(terrainPos.z / data.size.z * detailResolution);
        int size = Mathf.CeilToInt(radius / data.size.x * detailResolution);

        int[,] cleared = new int[size, size];
        data.SetDetailLayer(centerX - size / 2, centerY - size / 2, detailLayer, cleared);
    }

If it is the same terrain as the target terrain in ontriggerenter, the cleargrass function is called.

The grassClearRadius is the radius to clear the grass, and detailLayer is the layer of grass.

The original data of the terrain is not destroyed in “start”. (I remember that if I did not put this in, the data after the execution was finished was also edited.

ClearGrass deletes the grass in the specified area of the cube position.