[Editor Script] Modifying all Scenes / Prefabs

Hi, I have some MonoBehaviours that have Interfaces attached.
I want to write Editor code that gets all these interfaces and calls a Clear() method on them.

What the Clear() method does it, that it removes some references in serialized Inspector fields.
I already managed to call Clear, but this doesn’t save the changes (which can be inside Scenes or Prefabs).
How would you do it?

This is what I did so far:

            string[] assetsPaths = AssetDatabase.GetAllAssetPaths();

            foreach (string assetPath in assetsPaths)
            {
                Object[] data = LoadAllAssetsAtPath(assetPath);

                foreach (Object o in data)
                    if (o is IMyInterface interface)
                        interface.Clear();
            }

            Object[] LoadAllAssetsAtPath(string assetPath)
            {
                bool objectIsScene = typeof(SceneAsset) == AssetDatabase.GetMainAssetTypeAtPath(assetPath);
                return objectIsScene
                    ?
                    // prevent error "Do not use readobjectthreaded on scene objects!"
                    new[] {AssetDatabase.LoadMainAssetAtPath(assetPath)}
                    : AssetDatabase.LoadAllAssetsAtPath(assetPath);
            }

You could try adding a call to EditorUtility.SetDirty(o); after calling Clear and then after your loop call AssetDatabase.SaveAssets() and AssetDatabase.Refresh()

1 Like

Cool! That worked for most of them! 130 were dirty and now there is only 48 left, need to find out why it didn’t work on them. I suspect nested prefabs or something in that domain, need to investigate!

Edit: Found the cause. My check if they were dirty was wrong under some edge cases and The clear method has a tiny issue as-well.
So EditorUtility.SetDirty() did the trick. I didn’t even use the AssetDatabase Save / Refresh functions, but will keep that in mind.

1 Like