- Home /
change terrain texture and tree at runtime
hello, I checked the documentation but I have not found anything that I serve. how do I change at runtime the texture of the grass and the trees of the terrain?
Answer by ScroodgeM · Jul 17, 2012 at 07:23 PM
edit 19.07.2012
use this script. to see how it works do the following:
make a terrain and paint it with 3 any textures
add this script to any GameObject
assign terrain to script (Terrain field)
run the game
press 'space' button and check that on button pressing textures 1 and 2 are changing
read script's comments for more details
using UnityEngine; using System.Collections; public class TerrainTextureChanger : MonoBehaviour { public Terrain terrain; void Update() { if (Input.GetKeyDown(KeyCode.Space)) { //switch all painted in texture 1 to texture 2 UpdateTerrainTexture(terrain.terrainData, 1, 2); } if (Input.GetKeyUp(KeyCode.Space)) { //switch all painted in texture 2 to texture 1 UpdateTerrainTexture(terrain.terrainData, 2, 1); } } static void UpdateTerrainTexture(TerrainData terrainData, int textureNumberFrom, int textureNumberTo) { //get current paint mask float[, ,] alphas = terrainData.GetAlphamaps(0, 0, terrainData.alphamapWidth, terrainData.alphamapHeight); // make sure every grid on the terrain is modified for (int i = 0; i < terrainData.alphamapWidth; i++) { for (int j = 0; j < terrainData.alphamapHeight; j++) { //for each point of mask do: //paint all from old texture to new texture (saving already painted in new texture) alphas[i, j, textureNumberTo] = Mathf.Max(alphas[i, j, textureNumberFrom], alphas[i, j, textureNumberTo]); //set old texture mask to zero alphas[i, j, textureNumberFrom] = 0f; } } // apply the new alpha terrainData.SetAlphamaps(0, 0, alphas); } }
wrong answer below!
http://docs.unity3d.com/Documentation/ScriptReference/Terrain.html
look for
Terrain.renderer.material.SetTexture
should work. write here if you stuck somewhere on this way 8)
thanks for the reply .. unfortunately does not work, it returns this error:
An instance of type 'UnityEngine.Component' is required to access non static member 'renderer'.
this is my code
var TextureIn: Texture; function Update(){
Terrain.renderer.material.SetTexture = TextureIn;
}
or
var TextureIn: Texture; function Update(){
Terrain.renderer.material.maintexture = TextureIn;
}
"Terrain" word must be replaced with a link to your instance of Terrain
oops I forgot this line
var Terrain: GameObject;
but still does not work
There is no 'Renderer' attached to the "Terrain" game object, but a script is trying to access it.
I Had the same issue, and this code works fine for me! Thanks!!