うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】ツールバーメニュの AddComponent をスクリプトから呼び出す

どこで使うのか分かりませんが、ツールバーメニューの AddComponent を
スクリプトから呼び出すことができたのでメモ

f:id:hacchi_man:20200413231142p:plain:w400

using System;
using System.Reflection;
 
private static void AddComponentFromType(Type type, GameObject targetObj)
{
    var menuPath = "Component/Scripts/" + type.Namespace;
    var execMenu = "";
    foreach (var menu in Unsupported.GetSubmenus(menuPath))
    {
        var format = menu.Replace(" ", "");
        if (format == menuPath + "/" + type.Name)
        {
            execMenu = menu;
            break;
        }
    }
 
    if (string.IsNullOrEmpty(execMenu))
        return;
        
    typeof(EditorApplication).InvokeMember(
        "ExecuteMenuItemOnGameObjects",
        BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
        null,
        null,
        new object[]
        {
            execMenu, new GameObject[] {targetObj}
        }
    );
}