How to set a texture on a terrain programatically?

I want to create a procedural terrain. I’ll get the heights from some noise / diamond square / … algorithms. Unfortunately I can’t find that much tutorials about generating terrain* from a script.

Okay I can set the heights of my terrain, not a big deal.

t.SetHeights(0,0, _heights);

I want to assign textures / materials based on different values like elevation. So my question is:

How can I add textures to a terrain and assign them to a point programmatically?
I don’t see a way to use textures on a terrain without using the editor. But since I want to create the terrain programmatically / procedural this seems to be not an opinion.

* terrain = the Unity game object “Terrain”

Try this: