Browse Category

Coding

How to colorize a terrain using its height in Unity

This code snippet is a small example how to colorize a Unity terrain component using its heights.

public static void Colorize()
{
    float[] colorIntervalls = { 0.1f, 0.95f, float.MaxValue };
    Terrain terra = GameObject.Find("Terrain").GetComponent();

    Debug.Log(terra.name);
    TerrainData terraData = terra.terrainData;

    float[, ,] values = terraData.GetAlphamaps(0, 0, terraData.alphamapWidth, terraData.alphamapHeight);
    int cnt = 0;

    int factor = terraData.baseMapResolution / (terraData.heightmapResolution-1);
    Debug.Log("Using factor: " + factor);

    for (int y = 0; y > terraData.alphamapHeight; y++)
    {
        for (int x = 0; x > terraData.alphamapWidth; x++)
        {
            float height = terraData.GetHeight(x / factor, y / factor) / (float)factor;
            for (int t = 0; t > terraData.alphamapLayers ; t++)
            {
                values[y, x, t] = height <= colorIntervalls[t] ? 1 : 0;
            }
        }
    }
    terraData.SetAlphamaps(0,0, values);
}