ArgumentException: UnpackPrefabInstance must be called with a Prefab instance.

Greetings,
I’m developing a Monobehaviour script which is supposed to modify the prefab it is attached to.

In detail, I’m trying to remove all prefab’s children containing a Camera component (Editor time only).

To do so, I supposed to used PrefabUtility methods, in order to:

  1. GameObject prefab = PrefabUtility.GetOutermostPrefabInstanceRoot(this.gameObject);
  2. PrefabUtility.UnpackPrefabInstance(prefab, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);

After the Unpack I guess I have to PrefabUtility.SaveAsPrefabAsset and PrefabUtility.UnloadPrefabContents, but ArgumentException is triggered when using the UnpackPrefabInstance:

ArgumentException: UnpackPrefabInstance must be called with a Prefab instance.
UnityEditor.PrefabUtility.UnpackPrefabInstance (UnityEngine.GameObject instanceRoot, UnityEditor.PrefabUnpackMode unpackMode, UnityEditor.InteractionMode action) (at <17b72532ee2c4da1b6f632d3f1705fe0>:0)

I don’t get where the problem arises, since debugging the code I get correct references and path.

Thank you to everyone will answer

Are you calling this on a Prefab Asset? You can unpack Prefab instances in scenes (and in Prefab Mode). You can’t unpack Prefab Assets.

Thank you for your answer.
Yes, I was calling this on a Prefab Asset.
May I ask what the workflow of altering a Prefab Asset should be?

See the example code here:

2 Likes

Thank you, that worked smoothly.