Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Serialized Object Loses Data On Entering Play Mode

Discussion in 'Editor & General Support' started by Pasko70, Feb 9, 2021.

  1. Pasko70

    Pasko70

    Joined:
    Apr 6, 2020
    Posts:
    5
    Hey everyone,
    i'm altering my terrain with a script. These changes are permanent (they stay if I exit play mode). So I created a simple scriptable object that saves a two dimensional float array durring editor mode. Also i wrote a save and load function in an editor script. As long i stay in editor mode, i can save and load the current float array. But as soon as i enter playmode the array is gone.

    Scriptable Object:

    Code (CSharp):
    1. public class HeightMapScriptable : ScriptableObject
    2. {
    3.     public TerrainData terrainData;
    4.     private float[,] heightMapFloats;
    5.  
    6.  
    7.     public void SaveHeightMap()
    8.     {
    9.         float[,] temp = terrainData.GetHeights(0,0,terrainData.heightmapResolution,terrainData.heightmapResolution);
    10.         heightMapFloats = new float[temp.GetLength(0), temp.GetLength(1)];
    11.         for (int i = 0; i < temp.GetLength(0); i++)
    12.         {
    13.             for (int j = 0; j < temp.GetLength(1); j++)
    14.             {
    15.                 heightMapFloats[i,j] = temp[i,j];
    16.             }
    17.         }
    18.         EditorUtility.SetDirty(this);
    19.     }
    20.     public void LoadHeightMap()
    21.     {    
    22.         terrainData.SetHeights(0,0,heightMapFloats);
    23.     }
    24. }
    Editor Script:

    Code (CSharp):
    1. [CustomEditor(typeof(HeightMapScriptable))]
    2. public class HeightMapEditor : Editor
    3. {
    4.     public override void OnInspectorGUI()
    5.     {
    6.         HeightMapScriptable heightMap = (HeightMapScriptable)target;
    7.         if(GUILayout.Button("Save"))
    8.         {
    9.             heightMap.SaveHeightMap();
    10.             EditorUtility.SetDirty(heightMap);
    11.         }
    12.         if(GUILayout.Button("Load"))
    13.         {
    14.             heightMap.LoadHeightMap();
    15.         }
    16.         base.OnInspectorGUI();
    17.     }
    18. }
    I hope you can explain me what is happening.
    Greetings Pasko
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
    Unity cannot serialize multidimensional arrays.
     
    Pasko70 likes this.
  3. Pasko70

    Pasko70

    Joined:
    Apr 6, 2020
    Posts:
    5
    Ah ok thank you.
    For anyone reading this looking for a solution. I saved my 32 bit as rgba in all channels as 8 bit decoded, because i couldnt get the RFloat format to work. Actually in unity i use RFloat but saving it exr didnt work for me. As 4 channel png did just work fine.