Reputation: 496
I created a simple Texture2D in Unity as follows (simplified example):
Texture2D texture2d = new Texture2D(256,256);
for (int h = 0; h < texture2d.height; h++) {
for (int w = 0; w < texture2d.width ; w++) {
texture2d.SetPixel(w,h, Color.green);
}
}
How can I set this created Texture2D at a existing terrain, as ground texture?
Upvotes: 0
Views: 982
Reputation:
Because the built-in Terrain
shaders don't have a _MainTexture
property, you have to use a custom one: e.g. http://wiki.unity3d.com/index.php/TerrainFourLayerToon (place in a .shader
file)
from there you just need the appropriate code
//your code here
texture2d.Apply(); //missing in your code!
Material mat = new Material(Shader.Find("Terrain/Four Layer Toon Compat")); //from link
mat.SetTexture("_MainTex" , texture2d); //set the texture properties of the shader
mat.SetTexture("_MainTex2", texture2d);
mat.SetTexture("_MainTex3", texture2d);
mat.SetTexture("_MainTex4", texture2d);
Terrain terr = this.gameObject.GetComponent<Terrain>(); //get the terrain
terr.materialType = Terrain.MaterialType.Custom; //tell the terrain you want to manually assign its material
terr.materialTemplate = mat; //finally assign the material (and texture)
this code should work in Unity 5
If you are curious what any of these functions do, check https://docs.unity3d.com/Manual/SL-Reference.html for ShaderLab
, CG
, and the .shader
filetype
and http://docs.unity3d.com/ScriptReference/ under UnityEngine
-> Classes
for GameObject
, Material
, Shader
, Terrain
, and Texture2D
.
Upvotes: 1