unity-game-engineunity3d-terrain

Unity3D terrain SetAlphamaps method gives error: Assertion failed on expression 'spResult == PixelAccessReturnCode::kOk'


i am trying to make a script that creates a backup of my terrain so it can be restored after editing it at runtime.

SetHeightMap() restores my terrain as expected but SetAlphamaps gives me this error: Error

Here is my script. It is attached to the terrain object in my scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Backup : MonoBehaviour
{
    private float[,] _terrainHeightsBackup;
    private float[,,] _terrainAlphasBackup;
    private TerrainData _terrainBackup;
    
    private void Awake()
    {
        CreateBackupForTerrain();
    }

    private void OnApplicationQuit()
    {
        RestoreTerrain();
    }

    private void CreateBackupForTerrain()
    {
        Terrain terrain = Terrain.activeTerrain;
        var terrainData = terrain.terrainData;
        _terrainHeightsBackup = 
            terrainData.GetHeights(0, 0, 
                terrainData.heightmapResolution, 
                terrainData.heightmapResolution);
        _terrainAlphasBackup =
            terrainData.GetAlphamaps(0, 0, 
                terrainData.heightmapResolution, 
                terrainData.heightmapResolution);
    }
    
    private void RestoreTerrain()
    {
        Terrain terrain = Terrain.activeTerrain;
        TerrainData terrainData = terrain.terrainData;
        terrainData.SetAlphamaps(0, 0, _terrainAlphasBackup);
        terrainData.SetHeights(0, 0, _terrainHeightsBackup);
    }
}

Does anybody know how to solve this error?

I have tried to find more details about this specific error on Google but i could not find anyone else with this problem.


Solution

  • I encountered the same issue and fixed it

    Concerning AlphaMap you should use terrainData.alphamapResolution instead of terrainData.heightmapResolution In my case alphamaps have -1 length compared to heightmap (513x513 for heightmap, 512x512 for alphamap)