Unable To Add And Remove Gameobjects From Variant Prefabs Via Prefabutility

Hi friends,

I’m really struggling with finding a reliable way to edit prefabs through script, particularly variants.
All I want to do is the equivalent of this:

  • Open a prefab variant in a scene
  • Open in edit mode
  • Add and delete some objects from it and set some values
  • Save

I’ve tried InstantiatePrefab, LoadPrefabContents, Unpack, RecordModifications, ApplyOverrides, SaveAsPrefabAsset, they all end up either saving the variant as a new prefab instead of maintaining it’s variant status, or not keeping the changes, or adding the object but not applying it so it constantly has the + next to it. I’ve tried the example shown here , but I don’t want to add a component I want to delete and add game objects.
I’d really love a decent walkthrough or tutorial on what the PrefabUtility class is actually doing. All the current tutorials are for using the Editor interface rather than scripting.

My current attempt is this, but I have tried many others. This current incarnation doesn’t change the object at all.

string path = "path";
        GameObject originalObject = Resources.Load( path ) as GameObject;

        string assetPath = "assetpath.prefab";

        GameObject newObject = PrefabUtility.LoadPrefabContents( assetPath );
        PrefabUtility.UnpackPrefabInstance( newObject, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction );

        PrefabUtility.RecordPrefabInstancePropertyModifications( newObject );


        //Destroy any existing slots
        for( int i = newObject.childCount - 1; i > -1; i-- )
        {
            Transform child = newObject.GetChild(i);

            DestroyImmediate( child.gameObject );
        }

        //Add a slot for each slot in the original panel's data
        for( int i = 0; i < origObj.NumChildren; i++ )
        {
            int numberOfSlots = i + 1;
            GameObject newGm = new GameObject( "Slot" + numberOfSlots.ToString( "d2" ) );

            newGm.transform.parent = parent;

            newGm.transform.localPosition    = origObj.GetChild( i ).localPosition;
            newGm.transform.localRotation    = origObj.GetChild( i ).localRotation;
            newGm.transform.localScale        = origObj.GetChild( i ).localScale;

            Object slot = newGm.AddComponent<Object>();

        }

        PrefabUtility.ApplyObjectOverride( newObject, assetPath, InteractionMode.AutomatedAction );
        PrefabUtility.UnloadPrefabContents( newObject );

Any help on how to do the procedure in the bullet points above would be greatly appreciated!
I really like the new prefab process, but the PrefabUtility API is baffling

Hi @thom66

When modifying a variant like this there is 1 rule.
Don’t unpack the Variant, this will turn it into a regular prefab.

Of course this means you won’t be able to destroy GameObjects in variants only Components.

Thank you!

Looks like we’ll need a new approach.

Thom