Modify Prefab as it's being saved

When editing a prefab, I want to remove some game objects from the prefab just before it’s saved.

My scenario is that I’m using a Playable graph to preview sitting animations for seats. When previewing, a default avatar is spawned and I want to remove the avatar after I have done my edits so that it doesn’t get included in the final prefab.

Here’s is an example of what I’ve tried but maybe there’s a better solution:
#if UNITY_EDITOR
public class RemoveChildrenOfSeatOnSave : AssetModificationProcessor
{
static string OnWillSaveAssets(string paths)
{
foreach (string path in paths)
{
Debug.Log(path);
var furnitureItem = AssetDatabase.LoadAssetAtPath(path);
if (furnitureItem == null)
{
Debug.Log(“Furniture Item is null”);
continue;
}

            furnitureItem.seat.isTestingSitting = false;
            if (furnitureItem.seat.sittingTransform.childCount > 0)
            {
                furnitureItem.seat.sittingTransform.ClearChildrenImmediate();
            }

            EditorUtility.SetDirty(furnitureItem.gameObject);
        }
        return paths;
    }
}
#endif

Hey there! So, I noticed that the “ClearChildrenImmediate()” method you’re using isn’t a default method in Unity, so it’s not really clear what the method does, so just make sure that it’s working properly. If it’s not implemented correctly, it could cause some issues with the prefab later on by deleting more objects than you intended. As an alternative, instead of removing all of the child objects, you could use the Transform.Find() method to specifically target and remove the avatar game object. To do this, you can add the following code to your “foreach” loop. Just be careful to make sure you use the correct name for the avatar game object and that it’s actually a child of the parent object, otherwise the code might not work correctly and cause some errors.

if (furnitureItem.seat.sittingTransform.childCount > 0)
{
    Transform avatar = furnitureItem.seat.sittingTransform.Find("Avatar");
    if (avatar != null)
    {
        GameObject.DestroyImmediate(avatar.gameObject);
    }
}