Copy a prefab that is already instanced on the hierarchy and keep the overrides

It’s an editor script.

I have a GameObject that is a prefab or part of a prefab.

I check it using:

return (PrefabUtility.GetPrefabAssetType(prefab) == PrefabAssetType.Regular ||
                    PrefabUtility.GetPrefabAssetType(prefab) == PrefabAssetType.Variant);

Then I get the first parent prefab by doing:

parentPrefab = PrefabUtility.GetNearestPrefabInstanceRoot(obj);

If I instantiate it , I get a NULL result.

objCopy = PrefabUtility.InstantiatePrefab(parentPrefab, Utils.GetObjScene(parentPrefab)) as GameObject;  <-- Returns NULL

What I do is find the linked prefab in disk (in the project view) by using:

var source = PrefabUtility.GetCorrespondingObjectFromSource(refData.objRef);
objCopy = PrefabUtility.InstantiatePrefab(source, Utils.GetObjScene(parentPrefab)) as GameObject;

And this works. But the new instance doesn’t contain any of the overrides applied to the first object.
I want an exact copy of the first prefab (variable name : obj)

Trying to get the list of Overrides and then apply them to the new instance seems impossible because applying overrides is only done to an asset path, to consolidate it. I haven’t found a way to do this but setting the property mods, no idea if this also keeps objects additions and other overrides.

var ovr = PrefabUtility.GetPropertyModifications(parentPrefab);
                    PrefabUtility.SetPropertyModifications(objCopy, ovr);

How do I create an exact copy of a prefab with its overrides via PrefabUtility.InstantiatePrefab?

FYI, This is related to this other post in Reddit:
https://www.reddit.com/r/unity/comments/tbdfoe/prefabutilityinstantiateprefab_returns_null_and_i/

Other linked questions:

1 Like

@Darkgaze
post here for anyone come across!
Just pull my hair out since trying a lot of other method and they don’t work.
They are PrefabUtility.GetPrefabInstanceHandle, PrefabUtility.GetNearestPrefabInstanceRoot, all bs methods!
Only this works!

if ( PrefabUtility.IsPartOfAnyPrefab(go))
 { 
var prefab = PrefabUtility.GetCorrespondingObjectFromSource(go); 
return (GameObject)PrefabUtility.InstantiatePrefab(prefab); 
}
1 Like