コガネブログ

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

【Unity】Tilemap の Tile Palette で選択されているツールをスクリプトから変更する方法

ソースコード

using System;
using System.Reflection;
using UnityEditor;

public static class GridPaintPaletteWindowUtils
{
    private const BindingFlags BINDING_ATTR = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic;

    private static readonly Assembly   m_assembly         = typeof( AssetDatabase ).Assembly;
    private static readonly Type       m_type             = m_assembly.GetType( "UnityEditor.GridPaintPaletteWindow" );
    private static readonly MethodInfo m_gridSelectKey    = m_type.GetMethod( "GridSelectKey", BINDING_ATTR );
    private static readonly MethodInfo m_gridMoveKey      = m_type.GetMethod( "GridMoveKey", BINDING_ATTR );
    private static readonly MethodInfo m_gridBrushKey     = m_type.GetMethod( "GridBrushKey", BINDING_ATTR );
    private static readonly MethodInfo m_gridRectangleKey = m_type.GetMethod( "GridRectangleKey", BINDING_ATTR );
    private static readonly MethodInfo m_gridPickerKey    = m_type.GetMethod( "GridPickerKey", BINDING_ATTR );
    private static readonly MethodInfo m_gridEraseKey     = m_type.GetMethod( "GridEraseKey", BINDING_ATTR );
    private static readonly MethodInfo m_gridFillKey      = m_type.GetMethod( "GridFillKey", BINDING_ATTR );

    public static void GridSelectKey()    => m_gridSelectKey.Invoke( null, new object[0] );
    public static void GridMoveKey()      => m_gridMoveKey.Invoke( null, new object[0] );
    public static void GridBrushKey()     => m_gridBrushKey.Invoke( null, new object[0] );
    public static void GridRectangleKey() => m_gridRectangleKey.Invoke( null, new object[0] );
    public static void GridPickerKey()    => m_gridPickerKey.Invoke( null, new object[0] );
    public static void GridEraseKey()     => m_gridEraseKey.Invoke( null, new object[0] );
    public static void GridFillKey()      => m_gridFillKey.Invoke( null, new object[0] );
}

使い方

using UnityEditor;

public class Example
{
    [MenuItem( "Tools/Hoge" )]
    private static void Hoge()
    {
        // 選択
        GridPaintPaletteWindowUtils.GridSelectKey();

        // 移動
        GridPaintPaletteWindowUtils.GridMoveKey();

        // ブラシ
        GridPaintPaletteWindowUtils.GridBrushKey();

        // 矩形
        GridPaintPaletteWindowUtils.GridRectangleKey();

        // スポイト
        GridPaintPaletteWindowUtils.GridPickerKey();

        // 削除
        GridPaintPaletteWindowUtils.GridEraseKey();

        // 塗りつぶし
        GridPaintPaletteWindowUtils.GridFillKey();
    }
}

これで Tile Palette で選択されているツールをスクリプトから変更できます

f:id:baba_s:20190928150014p:plain