Search Unity

Saving Data to Scriptable Object via SerializedObject

Discussion in 'Scripting' started by gilley033, May 24, 2019.

  1. gilley033

    gilley033

    Joined:
    Jul 10, 2012
    Posts:
    1,191
    Hello all,

    I am currently creating a custom editor window that allows the user to create/edit patterns for use with my Asset Store product, the Terrain Slicing & Dynamic Loading Kit. The patterns are saved in a scriptable object asset, and I am making proper use of the SerailzedObject and SerializedProperty classes to do that. However, in some cases I must save a lot of data, and so the save becomes time consuming (nearly 2 seconds).

    My current method involves using SerializedProperty.FindPropertyRelative to get the correct Serialized Properties, and I am caching these lookups where feasible to save on performance. However, during the save process, I must save an array of a custom class type (which has 4 distinct fields), the size of which can change on each save, so caching the properties in each custom class is not possible.

    I have changed some of my code to make use of the SerializedProperty.Next method, and using this method does indeed speed things up by a significant factor. However, I rely on the Serialized Properties being ordered a certain way, and I am worried that in later versions of Unity, this order may be changed. Is this a legitimate concern? Here is the specific code that uses the Next method . . .
    Code (CSharp):
    1. //start by skipping over some stuff
    2. patternElementsProp.Next(true);//now pointing at Array (seems to be an identifier)
    3. patternElementsProp.Next(true);//now pointing at size (size of the array)
    4. patternElementsProp.Next(true);//now pointing at data (not sure what this indicates
    5. patternElementsProp.Next(true);//now pointing at offsetFromMainCell
    6.                    
    7. for (int i = 0; i < patternElements.Count; i++)
    8. {
    9.     EditorPatternElement e = patternElements[i];
    10.  
    11.     patternElementsProp.Next(true);//now pointing at row of array element
    12.     patternElementsProp.intValue = e.offsetFromMainCell.row;
    13.     patternElementsProp.Next(true);//now pointing at column of array element
    14.     patternElementsProp.intValue = e.offsetFromMainCell.column;
    15.     patternElementsProp.Next(true);//now pointing at layer of array element
    16.     patternElementsProp.intValue = e.offsetFromMainCell.layer;
    17.     patternElementsProp.Next(true);//now pointing at LOD of array element
    18.     patternElementsProp.intValue = e.LOD;
    19.     patternElementsProp.Next(true);
    20.     patternElementsProp.Next(true);
    21. }
    I am also wondering if this is the fastest way to save large amounts of data in the editor. Is there a different way using SerializedObject's? Should I not use SerializedObjects? I am open to alternative ways of doing things if you have any suggestions!