public Terrain terrain;
[ContextMenu("CreateNT")]
void CreateNT () {
SaveTexture(CreateNormalTexture(terrain), "/Data/Terrains/TerrainNormals", "TerrainNormalTest");
}
static Texture2D CreateNormalTexture(Terrain terrain) {
var heightResolution = terrain.terrainData.heightmapResolution;
var onePerWidth = 1f / (heightResolution - 1);
var colors = new Color[heightResolution * heightResolution];
for (int i = 0, num = 0; i < heightResolution; i++) {
for (var j = 0; j < heightResolution; j++, num++) {
var n = terrain.terrainData.GetInterpolatedNormal(i * onePerWidth, j * onePerWidth);
colors[num] = new Color((n.x + 1f) * 0.5f, (n.z + 1f) * 0.5f, (n.y + 1f) * 0.5f);
}
}
var texture = new Texture2D(heightResolution, heightResolution, TextureFormat.RGB24, false);
texture.SetPixels(colors);
texture.Apply();
return texture;
}
static void SaveTexture(Texture2D texture, string _path, string _name){
byte[] bytes = texture.EncodeToPNG();
var dirPath = Application.dataPath + _path;
if (!System.IO.Directory.Exists(dirPath))
{
System.IO.Directory.CreateDirectory(dirPath);
}
System.IO.File.WriteAllBytes(dirPath + "/" + _name + ".png", bytes);
Debug.Log(bytes.Length / 1024 + "Kb was saved as: " + dirPath);
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();
#endif
}