因为内置Terrain
着色器没有_MainTexture
属性,所以您必须使用自定义着色器:例如http://wiki.unity3d.com/index.php/TerrainFourLayerToon(放在.shader
文件中)
从那里你只需要适当的代码
//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)
这段代码应该在 Unity 5 中工作
如果您对这些函数的作用感到好奇,请查看https://docs.unity3d.com/Manual/SL-Reference.html中的ShaderLab
、CG
和.shader
文件类型
和http://docs.unity3d.com/ScriptReference/下UnityEngine
->Classes
为GameObject
, Material
, Shader
,Terrain
和Texture2D
.