Continue(s)

Twitter:@dn0t_ GitHub:@ogrew

【Unity】UnityEditor.MenuItemで自分だけのメニューを追加する

Unityのエディタ拡張の方法の一つとして自作のメニューバーを作るときに使えるAttributeがあります。それがMenuItemってやつです。

一番単純な例として、Asset/Editor/CustomMenu.csというスクリプトを以下のように書きます。

using UnityEngine;
using UnityEditor;

public class CustomMenu
{
    [MenuItem("CustomMenu/CallCat")]
    private static void CallCat()
    {
        Debug.Log("cat");
    }
}

using UnityEditor;をしています。保存した後、スクリプトを右クリックしてメニューから「Refresh」を選択。コンパイルエラーなどが起きていなければ、おそらくメニューバーに「CustomMenu」という新しいタブができているはずです。実行すると…

f:id:taiga006:20200106185708p:plain

さらにこのように追加した機能にはホットキーを割り当てることもできます。 (この関数は空のテキストファイルを生成します。)

using UnityEngine;
using UnityEditor;
using System;
using System.IO;

public class CustomMenu
{

    [MenuItem("CustomMenu/MakeText &t")]
    private static void MakeText()
    {
        string path = "./Assets/test.txt";
        if (!File.Exists(path))
        {
            File.CreateText("./Assets/test.txt");
        }
        else
        {
            Debug.Log("test.txt is already exists.");
        }
    }
}

f:id:taiga006:20200106185935p:plain

基本的なキーはどれでも使えそうです。ただし特殊記号を使わないホットキーを設定する場合は注意が必要です。

To create a hotkey you can use the following special characters: % (ctrl on Windows, cmd on macOS), # (shift), & (alt). If no special modifier key combinations are required the key can be given after an underscore. For example to create a menu with hotkey shift-alt-g use "MyMenu/Do Something #&g". To create a menu with hotkey g and no key modifiers pressed use "MyMenu/Do Something _g".

スクリプトリファレンス - MenuItem (class in UnityEditor)

しかし、テキストなどに限らずファイルを新たに生成したい場合はメニューバーよりもプロジェクトビューのCreateなどからできたほうが便利そうです…はい、できます!

using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.IO;

public class CustomMenu
{
    [MenuItem("Assets/Create/Dragon")]
    private static void CreateDragon()
    {
        Debug.Log("Created Dragon!!");
    }
}

f:id:taiga006:20200106190139p:plain

ここではやりませんが、HierarchyビューのCreateからであったり、コンポーネントコンテキストメニューに対しても任意のメニューを追加することができます。

アレンジ度高い!

参考

docs.unity3d.com

kan-kikuchi.hatenablog.com