Dynamic create Terrain and change the material by Script

I want to create Terrain by the script,and I used the terrainData to Create a terrain.Now I want to give the terrain a material.But I have some questions:
when I write the code like:
ter.renderer.material = mat;

the Unity will give this exception:


MissingComponentException: There is no ‘Renderer’ attached to the “Terrain” game object, but a script is trying to access it.
You probably need to add a Renderer to the game object “Terrain”. Or your script needs to check if the component is attached before using it.


but when I add Renderer like this: ter.AddComponent(“Renderer”);

the Unity will give a Warning like this


Cannot add component of type ‘Renderer’ because it is abstract. Add component of type that is derived from ‘Renderer’ instead.


So I search this problem on Google.Some person said that I should use the MeshRenderer instead.So I Write the code like : ter.AddComponent(“MeshRenderer”);

but it also doesn’t work:


Can’t add component ‘MeshRenderer’ to Terrain because such a component is already added to the game object!


Now I do not know how to do, who can tell me. Thanks very much.I want to create the terrain dynamic and create the material dynamic by script.


Try setting the material with Terrain.materialTemplate. I can’t see this in the documentation but it works on my project (in some Editor code, didn’t try it at run-time)