Make terrain flat at runtime

Are there any simple ways to do this? I looked around a lot and couldn’t find anything helpful. I’m not very experienced with unity terrain and I need a quick way to make it flat at runtime, through code. Thanks in advance!

using UnityEngine;

public class test : MonoBehaviour {

	public Terrain terrain;
	int terrainX; 
	int terrainY;

	void Awake(){
		terrainX = terrain.terrainData.heightmapWidth;
		terrainY = terrain.terrainData.heightmapHeight;
		var heights = terrain.terrainData.GetHeights(0, 0, terrainX, terrainY);

		for (int x = 0; x < terrainX; x++) {
			for (int y = 0; y < terrainY; y++) {
				heights[x,y] = 0;
		terrain.terrainData.SetHeights(0, 0, heights);

A bit late response, but I ran into this problem and ended up here.
If you set the terrain’s heightmapResolution, the terrain data is lost, i.e. it gets flat.
I don’t know what it does with its properties, but it gets the job done.

terrain.terrainData.heightMapResolution = yourValue;

Just know that it rounds it to the nearest (correct me if I’m wrong) resolution of (2^n)+1;