How do you add terrain textures at runtime?

I’m trying to create a procedural world. The terrain height works perfectly, I got everything set up with PerlinNoise. But the texture is still missing.
I tried:
terrain.renderer.material.SetTexture ();
But it didn’t work as the terrainhas no mesh renderer attached.
So how can I add/change the texture of a terrain generated at runtime?

this was a quick test script that seemed to work. Please note this is in uJS :

#pragma strict

import System.Collections.Generic;

public var terrain : Terrain;
private var terrainData : TerrainData;

public var newTerrainTexture : Texture2D[];
var terrainTextureList : List.< SplatPrototype >; // private, public for testing

function Start() 
{
	if ( !terrain )
	{
		terrain = Terrain.activeTerrain;
	}
	
	terrainData = terrain.terrainData;
	
	// store existing textures
	var i : int = 0;
	
	terrainTextureList = new List.< SplatPrototype >();
	
	for ( i = 0; i < terrainData.splatPrototypes.Length; i ++ )
	{
		terrainTextureList.Add( terrainData.splatPrototypes *);*
  • }*

  • // add new textures*

  • var newSplat : SplatPrototype;*

  • for ( i = 0; i < newTerrainTexture.Length; i ++ )*

  • {*

  •  newSplat = new SplatPrototype();*
    

_ newSplat.texture = newTerrainTexture*;_
_
newSplat.tileSize = new Vector2( 15, 15 );_
_
newSplat.tileOffset = Vector2.zero;*_

* terrainTextureList.Add( newSplat );*
* }*

* // reapply splats to terrain*
* terrainData.splatPrototypes = terrainTextureList.ToArray();*

* // you may also need*
* // terrain.terrainData.RefreshPrototypes();*
* // terrain.Flush();*
}
Unity Scripting References :
* http://docs.unity3d.com/Documentation/ScriptReference/TerrainData-splatPrototypes.html_
* http://docs.unity3d.com/Documentation/ScriptReference/SplatPrototype.html_