Editor/PrefabTools.cs

Editor MCP toolset exposing prefab operations: create a prefab from a game object, list prefab instances, report instance overrides, apply overrides to the prefab file, revert changes and unlink instances. Each tool wraps EditorUtility.Prefabs calls with undo scopes and returns before/after state.

File AccessFile Access
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Editor;
using Editor.Mcp;
using Sandbox;
using static LevelTools.McpHelpers;

namespace LevelTools;

[McpToolset( "prefab", "Prefab files and their instances - make a prefab from an object, find instances, see per-property overrides, and apply, revert or unlink an instance" )]
public static class PrefabTools
{
    /// <summary>
    /// Save a game object and its children as a new prefab file, and turn the object into an instance
    /// of it. When the object is already part of a prefab instance, the engine replaces it with a
    /// linked clone, so the returned Id differs from the one given. The file is written immediately;
    /// the user can undo the change to the scene, but not the file.
    /// </summary>
    /// <param name="id">Game object id, from scene_tree or find_game_objects.</param>
    /// <param name="path">New prefab path relative to Assets, e.g. 'prefabs/crate.prefab'. Missing folders are created.</param>
    [McpTool( "prefab_create" )]
    public static object Create( string id, string path )
    {
        var go = FindByGuid( id );
        var full = AssetsPath( path );

        if ( File.Exists( full ) )
            throw new Exception( $"'{path}' already exists - use prefab_apply to update an existing prefab, or pick a new path" );

        var session = SessionOf( go );
        var before = new { Id = go.Id, WasInstanceOf = go.IsPrefabInstance ? OutermostRoot( go ).PrefabInstanceSource : null };

        Directory.CreateDirectory( Path.GetDirectoryName( full ) );

        using var sceneScope = session.Scene.Push();
        GameObject result;
        var undo = session.UndoScope( "Convert to Prefab" ).WithGameObjectChanges( go, GameObjectUndoFlags.All ).WithGameObjectCreations();

        // An instance is replaced by a clone and destroyed; without recording that, undo removes the clone and loses the object
        if ( go.IsPrefabInstance )
            undo = undo.WithGameObjectDestructions( go );

        using ( undo.Push() )
        {
            result = EditorUtility.Prefabs.ConvertGameObjectToPrefab( go, full );
        }

        if ( result is null )
            throw new Exception( $"The engine couldn't write '{path}' - a prefab can't contain an instance of itself; read_console has the reason" );

        return new { Id = result.Id, Path = result.PrefabInstanceSource, Before = before, After = new { IsInstance = result.IsPrefabInstance } };
    }

    /// <summary>
    /// List the prefab instances in the open scene - outermost instances only, so a prefab nested inside
    /// another instance is not counted. Returns each instance's id, prefab and whether it has overrides.
    /// </summary>
    /// <param name="path">Only instances of this prefab, relative to Assets, e.g. 'prefabs/crate.prefab'. Empty lists every instance.</param>
    /// <param name="limit">How many instances to return. Default 50, max 1000. Total is always the full count.</param>
    /// <param name="offset">How many instances to skip, for paging.</param>
    [McpTool.ReadOnly( "prefab_get_instances" )]
    public static object GetInstances( string path = "", [Sandbox.Range( 0, 1000 )] int limit = 50, [Sandbox.Range( 0, int.MaxValue )] int offset = 0 )
    {
        var want = NormalizePrefabPath( path );

        var all = ReadScene().GetAllObjects( false )
            .Where( x => EditorUtility.Prefabs.IsOuterMostPrefabRoot( x ) )
            .Where( x => want.Length == 0 || string.Equals( NormalizePrefabPath( x.PrefabInstanceSource ), want, StringComparison.OrdinalIgnoreCase ) )
            .ToList();

        var page = all.Skip( offset ).Take( limit ).Select( x => new
        {
            x.Id,
            x.Name,
            Prefab = x.PrefabInstanceSource,
            Position = x.WorldPosition,
            IsModified = EditorUtility.Prefabs.IsInstanceModified( x ),
        } ).ToList();

        return new { Total = all.Count, Showing = page.Count, Instances = page };
    }

    /// <summary>
    /// Show how a prefab instance differs from its prefab: the properties overridden on each object and
    /// component, and the objects and components added to the instance. Give any object in the instance;
    /// the report covers the whole outermost instance. Position, rotation, scale and name on the instance
    /// root are not counted, as in the inspector.
    /// </summary>
    /// <param name="id">Id of any game object in the instance, from scene_tree or prefab_get_instances.</param>
    [McpTool.ReadOnly( "prefab_get_overrides" )]
    public static object GetOverrides( string id )
    {
        return Overrides( FindByGuid( id ) );
    }

    /// <summary>
    /// Write an instance's overrides back into its prefab file, so every instance picks them up. On the
    /// outermost root the whole instance is written; on an object inside it, only that part; on an object
    /// added to the instance (prefab_get_overrides lists them), it is added to the prefab with its children. The file
    /// is written immediately and the user cannot undo it; the scene is flagged unsaved, as the editor's own
    /// Apply does. Returns the overrides before and after.
    /// </summary>
    /// <param name="id">Id of the instance root, or of a nested prefab instance inside it.</param>
    [McpTool( "prefab_apply" )]
    public static object Apply( string id )
    {
        var go = FindByGuid( id );
        var root = OutermostRoot( go );
        var session = SessionOf( go );
        var before = Overrides( go );

        // An added object has no counterpart in the prefab for ApplyGameObjectInstanceChangesToPrefab to
        // update (it throws on null), so it is added instead, as the editor's menu does
        GameObject added = null;
        for ( var x = go; x != root; x = x.Parent )
        {
            if ( EditorUtility.Prefabs.IsGameObjectAddedToInstance( x ) ) added = x;
        }

        if ( added is not null && added != go )
            throw new Exception( $"{go.Id} is inside {added.Id}, which was added to the instance - apply {added.Id} to add it to the prefab with its children" );

        using var sceneScope = session.Scene.Push();

        if ( go == root )
            EditorUtility.Prefabs.WriteInstanceToPrefab( go );
        else if ( added == go )
            EditorUtility.Prefabs.AddInstanceAddedGameObjectToPrefab( go );
        else
            EditorUtility.Prefabs.ApplyGameObjectInstanceChangesToPrefab( go );

        session.HasUnsavedChanges = true;

        return new { Before = before, After = Overrides( FindByGuid( id ) ) };
    }

    /// <summary>
    /// Throw away an instance's overrides on this object and everything under it, so it matches its prefab
    /// again. The user can undo this. Returns the overrides before and after.
    /// </summary>
    /// <param name="id">Id of any game object in the instance; the revert covers it and its children.</param>
    [McpTool( "prefab_revert" )]
    public static object Revert( string id )
    {
        var go = FindByGuid( id );
        var session = SessionOf( go );
        var before = Overrides( go );

        using var sceneScope = session.Scene.Push();
        // Properties alone snapshots only the object's own fields: a component-only revert would record no undo
        // step (the editor's own Revert menu has this bug), so capture components and children too
        using ( session.UndoScope( "Revert Changes" ).WithGameObjectChanges( go, GameObjectUndoFlags.All ).Push() )
        {
            EditorUtility.Prefabs.RevertGameObjectInstanceChanges( go );
        }

        return new { Before = before, After = Overrides( FindByGuid( id ) ) };
    }

    /// <summary>
    /// Unlink a prefab instance so it becomes ordinary game objects; prefabs nested inside it stay linked.
    /// Only the outermost instance root can be unlinked. The user can undo this.
    /// </summary>
    /// <param name="id">Id of the outermost instance root, from prefab_get_instances.</param>
    [McpTool( "prefab_break" )]
    public static object Break( string id )
    {
        var go = FindByGuid( id );
        var root = OutermostRoot( go );

        // BreakFromPrefab does nothing, silently, on anything but the outermost root
        if ( root != go )
            throw new Exception( $"{go.Id} is inside the instance rooted at {root.Id} - unlink the outermost instance {root.Id}" );

        var session = SessionOf( go );
        var before = new { Prefab = go.PrefabInstanceSource };

        using var sceneScope = session.Scene.Push();
        using ( session.UndoScope( "Unlink From Prefab" ).WithGameObjectChanges( go, GameObjectUndoFlags.All ).Push() )
        {
            go.BreakFromPrefab();
        }

        return new { Id = go.Id, Before = before, After = new { IsInstance = go.IsPrefabInstance } };
    }

    static object Overrides( GameObject go )
    {
        var root = OutermostRoot( go );
        var overrides = new List<object>();
        var addedObjects = new List<object>();
        var addedComponents = new List<object>();

        foreach ( var obj in root.GetAllObjects( false ) )
        {
            // An instance placed inside another instance counts as added to that one, not to itself
            if ( obj != root && EditorUtility.Prefabs.IsGameObjectAddedToInstance( obj ) )
            {
                addedObjects.Add( new { obj.Id, obj.Name } );
                continue;
            }

            if ( !EditorUtility.Prefabs.IsGameObjectInstanceModified( obj ) ) continue;

            // Position, rotation and scale are serialized on the transform, the rest on the object
            var own = OverriddenProperties( obj.GetSerialized() ).Concat( OverriddenProperties( obj.Transform.GetSerialized() ) ).Distinct().ToList();
            if ( own.Count > 0 )
                overrides.Add( new { GameObjectId = obj.Id, Target = "GameObject", ComponentId = (Guid?)null, Properties = own } );

            foreach ( var comp in obj.Components.GetAll() )
            {
                if ( EditorUtility.Prefabs.IsComponentAddedToInstance( comp ) )
                {
                    addedComponents.Add( new { GameObjectId = obj.Id, ComponentId = comp.Id, Type = comp.GetType().Name } );
                    continue;
                }

                if ( !EditorUtility.Prefabs.IsComponentInstanceModified( comp ) ) continue;

                var props = OverriddenProperties( comp.GetSerialized() ).ToList();
                if ( props.Count > 0 )
                    overrides.Add( new { GameObjectId = obj.Id, Target = comp.GetType().Name, ComponentId = (Guid?)comp.Id, Properties = props } );
            }
        }

        return new
        {
            Id = root.Id,
            Prefab = root.PrefabInstanceSource,
            IsModified = EditorUtility.Prefabs.IsInstanceModified( root ),
            Overrides = overrides,
            AddedObjects = addedObjects,
            AddedComponents = addedComponents,
        };
    }

    static IEnumerable<string> OverriddenProperties( SerializedObject so )
    {
        return so.Where( EditorUtility.Prefabs.IsPropertyOverridden ).Select( p => p.Name );
    }

    // OutermostPrefabInstanceRoot is internal, so walk up to the root the public check recognises
    static GameObject OutermostRoot( GameObject go )
    {
        for ( var x = go; x is not null; x = x.Parent )
        {
            if ( EditorUtility.Prefabs.IsOuterMostPrefabRoot( x ) ) return x;
        }

        throw new Exception( $"{go.Id} isn't part of a prefab instance - prefab_get_instances lists the instances in the scene" );
    }

    static string NormalizePrefabPath( string path )
    {
        return (path ?? "").Replace( '\\', '/' ).TrimStart( '/' );
    }
}