How to apply terrain texture at 'gamestart'?

Hi, Im fairly new to this.
Im trying to make a random map. meaning that when the game starts, the game lowers and raises terrain randomly. This is working. Then I need it to apply a texture to the terrain. (at gamestart the terrain has no texture applied).

in the below code, the texture should be applied in the applytexture function. And as you can see I have tried both with settexture and maintexture functions, but nothing happens. (I have associated the texture with the terrain in unity)
Script:

public class terrain_altering : MonoBehaviour {

	public Terrain terrain;
	public Texture texture;
	// Use this for initialization
	void Start () {
  		maketerrain ();
 		applytexture ();
 	}
	
	// Update is called once per frame
	 void Update () {
	
 	}

	void maketerrain(){
		int xresolution = terrain.terrainData.heightmapWidth;
		int zresolution = terrain.terrainData.heightmapHeight;
		float [,] heights =terrain.terrainData.GetHeights (0, 0, xresolution, zresolution);
		float h = 0.0001f;
		float r = 0.0f;
		 for (int x = 0; x < xresolution; x++) {
			for (int z = 0; z < zresolution; z++) {
				r = Random.value;
				if (r >= 0.005f) {
					h = 0.008f;
				}
				else {
					h = 0.0001f;
				}
				heights [x, z] = h;
			}
		}
		terrain.terrainData.SetHeights (0, 0, heights);
	}
		
	void applytexture(){
		//terrain.renderer.material.SetTexture = texture;
		terrain.renderer.material.mainTexture = texture;
	}
}

If the scripting is wrong for applying texture, then how do I do this in a simple way?

You are probably getting a null reference exception at runtime. The terrain doesn’t have a renderer, meaning you can’t access terrain.renderer. Instead you need to change the texture in terrainData.