在Unity中设置地形生成的Texture2D

本文关键字:Texture2D Unity 设置 | 更新日期: 2023-09-27 18:10:08

我在Unity中创建了一个简单的Texture2D,如下(简化的例子):

   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);
        }
    }

我如何在现有地形上设置这个创建的Texture2D,作为地面纹理?

在Unity中设置地形生成的Texture2D

因为内置的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查看ShaderLabCG.shader文件类型

GameObjectMaterialShaderTerrainTexture2DUnityEngine -> Classes

和http://docs.unity3d.com/ScriptReference/