- Home /
Change and add Terrain Texture During Runtime
Hey All,
I'm trying to add a terrain texture on top of an existing texture during run-time on top of the terrain texture that exists. This is to emulate the triggering of different "Layers " for the terrain
I have looked into http://answers.unity3d.com/questions/285816/change-terrain-texture-and-tree-at-runtime.html?sort=oldest
However, It doesn't fit my needs and I don't know how to modify the script because its in C#
Here is a bit of script I have come up with
var TextureIn: Texture;
var plane: GameObject;
function Update(){
if(Input.GetKeyDown("4"))
{
plane.renderer.material.SetTexture("_MainTex", TextureIn);
}
}
I get a error that "There is no 'Renderer' attached to the "terrain" game object but a script is trying to access it"
Answer by Murkas · Mar 21, 2014 at 01:22 PM
Was searching for the same and figured it out by reading the ScriptReference of TerrainData.
You have to use the splatPrototypes property, here is an example:
using UnityEngine;
using System.Collections;
public class TerrainTextureAssigner : MonoBehaviour
{
public Texture2D[] TerrainTextures;
public TerrainData terraindata;
public Terrain terrain;
public void CreateTerrain(){
SplatPrototype[] tex = new SplatPrototype [TerrainTextures.Length];
for (int i=0; i<TerrainTextures.Length; i++) {
tex [i] = new SplatPrototype ();
tex [i].texture = TerrainTextures [i]; //Sets the texture
tex [i].tileSize = new Vector2 (1, 1); //Sets the size of the texture
}
terraindata.splatPrototypes = tex;
terrain = Terrain.CreateTerrainGameObject (terraindata).GetComponent<Terrain> ();
}
}
In this example you have to assign your textures and the terraindata, then you call CreateTerrain() and you get your Terrain. Of course you should also change the alphamap of the terraindata.
More about SplatPrototypes, Getting Alphamaps and Setting Alphamaps.