Updating a created scriptable object using an editor script.

I am working on creating a tool to take our JSON item DB from a custom tool and convert them into Scriptable Objects. I’ve created an editor script that currently correctly creates a scriptable object.

var so = ScriptableObject.CreateInstance(itemClass);
//assign values here
AssetDatabase.CreateAsset(so, "Assets/Items/" + so.name + ".asset");

Hypothetically this contains a color for the item, and I assign it to a script that updates the material color to blue. Later our json says the item should be red. Running the script again causes the SO to update correctly BUT breaks the reference to the item in the scene(which weirdly doesn’t error but instead just stays as the old copy) I need the item to be updated instead of creating over the existing one.

Currently I have done some googling which says I have to get the asset and then update it, set it to dirty and then save which is not working:

var existingSO = AssetDatabase.LoadAssetAtPath(
    "Assets/Items/" + so.name + ".asset", typeof(ScriptableObject)
);			
existingSO = so;
EditorUtility.SetDirty(existingSO);
AssetDatabase.SaveAssets();

I can’t see any kind of “UpdateAsset” function for scriptable objects anywhere so I’m not sure how else to update the values.

This code will do what you want.

*** It only work in editor***

*** If you want to create a new scriptable object remember to keep “.asset” end of the file name.

[MenuItem("Sajjad/Save")]
     public static void Save()
        {
            string[] result = AssetDatabase.FindAssets("SavedAsset");
            YourScriptableObject yourObject= null;
    
            if (result.Length > 1)
            {
                Debug.LogError("More than 1 Asset founded");
                return;
            }
    
            if(result.Length == 0)
            {
                Debug.Log("Create new Asset");
                yourObject = ScriptableObject.CreateInstance<YourScriptableObject >();
                AssetDatabase.CreateAsset(yourObject, @"Assets\SavedAsset.asset");
            }
            else
            {
                string path = AssetDatabase.GUIDToAssetPath(result[0]);
                yourObject= (YourScriptableObject )AssetDatabase.LoadAssetAtPath(path, typeof(YourScriptableObject ));
                Debug.Log("Found Asset File !!!");
            }
    
            // Do your changes
    
            EditorUtility.SetDirty(yourObject);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

Did you find a solution to this? I am facing the same issue.