I have the following code to mimic the “Apply” button in an editor script, and it works great to automatically force any changes I apply to my prefab in the Scene view to the prefab it draws from in the Project view. However, this ONLY works if I make changes to the parent object of the prefab. If I make changes to a child in the prefab, when it subsequently applies the changes, the parent object becomes the child object that I modified, which is not the functionality I want. Obviously, the GetPrefabParent
is working as intended, but I’m looking for something different. Ideally, when I edit the child, it would apply the changes only to the same child in the Project view, not replace the parent. However, I don’t see how to do this.
if (GUI.changed) {
EditorUtility.SetDirty(EI);
if (PrefabUtility.GetPrefabType(Selection.objects[0]) == PrefabType.PrefabInstance) {
PrefabUtility.ReplacePrefab(Selection.objects[0], PrefabUtility.GetPrefabParent(Selection.objects[0]), ReplacePrefabOptions.ConnectToPrefab);
}
}
To do this, I had to specify which part I wanted to update the prefab origin with from my selection. Before, I was simply replacing the prefab origin with my selection (which was the child). I had to change it so it replaced the prefab origin (which was a parent) with the parent of the child I had selected in the “Hierarchy” View.
if (GUI.changed) {
var selectedGameObject : GameObject;
var selectedPrefabType : PrefabType;
var parentGameObject : GameObject;
var prefabParent : UnityEngine.Object;
// Get currently selected object in "Hierarchy" view and store
// its type, parent, and the parent's prefab origin
selectedGameObject = Selection.gameObjects[0];
selectedPrefabType = PrefabUtility.GetPrefabType(selectedGameObject);
parentGameObject = selectedGameObject.transform.root.gameObject;
prefabParent = PrefabUtility.GetPrefabParent(selectedGameObject);
// Notify the script this is modifying that something changed
EditorUtility.SetDirty(target);
// If the selected object is an instance of a prefab
if (selectedPrefabType == PrefabType.PrefabInstance) {
// Replace parent's prefab origin with new parent as a prefab
PrefabUtility.ReplacePrefab(parentGameObject, prefabParent,
ReplacePrefabOptions.ConnectToPrefab);
}
}