Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Is there a faster way to save assets (ScriptableObjects) that have been programmatically changed?

Discussion in 'Scripting' started by fiveampsoftware, Jul 8, 2021.

  1. fiveampsoftware

    fiveampsoftware

    Joined:
    Feb 9, 2015
    Posts:
    33
    We have flows where we programmatically change / update ScriptableObjects in our projects. After we change these assets we found the best method to ensure we actually see these changes written to disk and reflect in source control is to call:
    Code (CSharp):
    1. UnityEditor.EditorUtility.SetDirty(this);
    2. UnityEditor.AssetDatabase.SaveAssets();
    3. UnityEditor.AssetDatabase.Refresh();
    The call: AssetDatabase.SaveAssets is very S L O W. Is there any other faster way to modify assets and ensure they are actually written to disk?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,514
    I usually use
    Undo.RecordObject()
    (or its plural form) when modifying assets such as ScriptableObjects. This give you undo ability, plus it seems performant to me. If you have massive amounts of data, it might not be though, so the solution might to only target what actually changed.
     
  3. fiveampsoftware

    fiveampsoftware

    Joined:
    Feb 9, 2015
    Posts:
    33
    Just did a test and I can confirm this does not write the changes to disk. If you subsequently save through other methods these changes will be written to disk, but after using this method alone -- you cannot be confident the disk matches your Editor.
     
  4. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,732
    I've found the only completely reliable way to make sure changes to ScriptableObject assets (and most other custom editor stuff) are serialized is to do everything via the SerializedObject and SerializedProperty APIs.