コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】Inspector の「Expand All Components」「Collapse All Components」をスクリプトから呼ぶ方法

ソースコード

using System;
using System.Reflection;
using UnityEditor;

namespace Kogane.Internal
{
    public static class PropertyEditorInternal
    {
        private const BindingFlags BINDING_ATTRS = BindingFlags.Instance | BindingFlags.NonPublic;

        private static readonly Type TYPE = typeof( Editor ).Assembly.GetType( "UnityEditor.PropertyEditor" );

        public static void ExpandAllComponents( EditorWindow propertyEditor )
        {
            var method = TYPE.GetMethod( nameof( ExpandAllComponents ), BINDING_ATTRS );
            method.Invoke( propertyEditor, Array.Empty<object>() );
            propertyEditor.Repaint();
        }

        public static bool IsAnyComponentCollapsed( EditorWindow propertyEditor )
        {
            var method = TYPE.GetMethod( nameof( IsAnyComponentCollapsed ), BINDING_ATTRS );
            return ( bool )method.Invoke( propertyEditor, Array.Empty<object>() );
        }

        public static void CollapseAllComponents( EditorWindow propertyEditor )
        {
            var method = TYPE.GetMethod( nameof( CollapseAllComponents ), BINDING_ATTRS );
            method.Invoke( propertyEditor, Array.Empty<object>() );
            propertyEditor.Repaint();
        }

        public static bool IsAnyComponentExpanded( EditorWindow propertyEditor )
        {
            var method = TYPE.GetMethod( nameof( IsAnyComponentExpanded ), BINDING_ATTRS );
            return ( bool )method.Invoke( propertyEditor, Array.Empty<object>() );
        }
    }
}

使用例

using System;
using System.Linq;
using Kogane.Internal;
using UnityEditor;
using UnityEngine;

public static class Example
{
    private static readonly Type TYPE = typeof( Editor ).Assembly.GetType( "UnityEditor.PropertyEditor" );

    [MenuItem( "Tools/Expand All Components", true )]
    private static bool IsAnyComponentCollapsed()
    {
        return PropertyEditorInternal.IsAnyComponentCollapsed( GetPropertyEditor() );
    }

    [MenuItem( "Tools/Expand All Components" )]
    private static void ExpandAllComponents()
    {
        PropertyEditorInternal.ExpandAllComponents( GetPropertyEditor() );
    }

    [MenuItem( "Tools/Collapse All Components", true )]
    private static bool IsAnyComponentExpanded()
    {
        return PropertyEditorInternal.IsAnyComponentExpanded( GetPropertyEditor() );
    }

    [MenuItem( "Tools/Collapse All Components" )]
    private static void CollapseAllComponents()
    {
        PropertyEditorInternal.CollapseAllComponents( GetPropertyEditor() );
    }

    private static EditorWindow GetPropertyEditor()
    {
        return Resources
                .FindObjectsOfTypeAll( TYPE )
                .FirstOrDefault() as EditorWindow
            ;
    }
}