- Home /
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?
I only found out how to change the texture via splatTexture, but not how to add a new one. Could you give me an example? ("public Texture baseTexture; terrain.setTexture(baseTexture)", something like that)
I've never actually added a texture to the terrain at runtime, but I did a quick test, have posted as answer.
Answer by AlucardJay · Feb 02, 2014 at 07:37 AM
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[i] );
}
// add new textures
var newSplat : SplatPrototype;
for ( i = 0; i < newTerrainTexture.Length; i ++ )
{
newSplat = new SplatPrototype();
newSplat.texture = newTerrainTexture[i];
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 :