For my real-time strategy game Zyrtuul I need to be able to load different landscapes at run-time. A fundamental part of this is loading terrain heightmap data from script. I implemented this last night. I noticed that many people have been asking how to do this online, but I did not see any complete solutions presented. It turned out to be significantly easier than anticipated. This implementation allows you to save your heightmap using any image format (I assume it is saved in Assets/Resources/Heightmaps). Simply attach this script to your terrain object and it will load up the specified heightmap automatically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class TerrainLoader : MonoBehaviour | |
{ | |
// Private methods. | |
//---------------------------------------------------------------------------------------------- | |
private void Start() | |
{ | |
m_terrain = ( Terrain ) gameObject.GetComponent( "Terrain" ); | |
m_resolution = m_terrain.terrainData.heightmapResolution; | |
m_heightValues = new float[ m_resolution, m_resolution ]; | |
LoadHeightmap( "Heightmap1" ); | |
} | |
private void LoadHeightmap( string filename ) | |
{ | |
// Load heightmap. | |
Texture2D heightmap = ( Texture2D ) Resources.Load( "Heightmaps/" + filename ); | |
// Acquire an array of colour values. | |
Color[] values = heightmap.GetPixels(); | |
// Run through array and read height values. | |
int index = 0; | |
for ( int z = 0; z < heightmap.height; z++ ) | |
{ | |
for ( int x = 0; x < heightmap.width; x++ ) | |
{ | |
m_heightValues[ z, x ] = values[ index ].r; | |
index++; | |
} | |
} | |
// Now set terrain heights. | |
m_terrain.terrainData.SetHeights( 0, 0, m_heightValues ); | |
} | |
// Member variables. | |
//---------------------------------------------------------------------------------------------- | |
private Terrain m_terrain = null; | |
private float[ , ] m_heightValues = null; | |
private int m_resolution = 0; | |
} |