How do I "Apply" a prefab if I have access to one of its instances via code?

If I modify something in an instance of my prefab, how can I “Apply” the changes to the prefab? (Just like clicking “Apply” from the editor)

Thanks!

If you want to recreate the behaviour of the Apply button in an editor script, this works (assuming instance is your disconnected scene instance)

PrefabUtility.ReplacePrefab(instance, PrefabUtility.GetPrefabParent(instance), ReplacePrefabOptions.ConnectToPrefab);

One caveat to the above answer: If ‘instance’ is actually a child object inside the prefab, that one line of code will do the wrong thing. You want this instead:

                    var instanceRoot = PrefabUtility.FindRootGameObjectWithSameParentPrefab(target.gameObject);
                    var targetPrefab = UnityEditor.PrefabUtility.GetPrefabParent(instanceRoot);

                    PrefabUtility.ReplacePrefab(
                            instanceRoot,
                            targetPrefab,
                            ReplacePrefabOptions.ConnectToPrefab
                            );

From Unity source:

UnityEngine.Object prefabParent = PrefabUtility.GetPrefabParent(target);
GameObject gameObject = PrefabUtility.FindValidUploadPrefabInstanceRoot(target);
PrefabUtility.ReplacePrefab(gameObject, prefabParent, ReplacePrefabOptions.ConnectToPrefab);