Apply prefab change though script without loosing reference

Hey, I’ve been stuck for a while now. My problem is that i want to apply changes to a prefab made though an editor script, but whenever i do so(though misc methods), it either breaks the prefab reference, or Unity reverts it when its closed. So, i am wondering, is there any way to do something like PrefabUtility.ApplyChanges() or similar?

I have seen other posts where they suggest PrefabUtility.Replace(), but it makes no sense for me. First of all it breaks connection, secondly it actually requires an object.
I am loading the prefab i want though Assetdatabase, because PrefabUtility.Instantiate() requires an object, which i don’t have, as the class is static.

It is quite mindblowing for me that its SOOOO hard to apply a prefab change through script…

PS: could anyone explain to my why Unity reverts prefab changes when you close Unity?

If you are changing the Prefab Asset in the Project you should just use EditorUtility.SetDirty(), I believe. Unity says it’s going to be deprecated, but I think that’s for scene objects. You can force the AssetDatabase to SaveAssets, if you don’t want closing it to revert the changes. But it’s kind of wrong to automatically save the user’s assets for them, IMO.

If you are wanting to change an instance of a prefab and apply it to the prefab (like pressing the “Apply” button in the inspector), you should use PrefabUtility.ReplacePrefab() as you’ve heard. It shouldn’t break the connection if you pass the ReplacePrefabOptions.ConnectToPrefab as the last parameter:

PrefabUtility.ReplacePrefab(prefabInstance, sourcePrefab, ReplacePrefabOptions.ConnectToPrefab);