Unity HierarchyにC#スクリプトをドラッグ&ドロップできるようにするエディター拡張

More than 1 year has passed since last update.

Unity5 HierarchyにC#スクリプトをドラッグ&ドロップできるようにするエディター拡張

image

image

ソースコード

CustomHierarchy.cs
using UnityEngine;
using UnityEditor;

[InitializeOnLoad]
public static class CustomHierarchy
{
    static EventType event_last;
    static MonoScript[] mss;

    static CustomHierarchy()
    {
        mss = Resources.FindObjectsOfTypeAll<MonoScript>();
        EditorApplication.hierarchyWindowItemOnGUI += OnGUI;
    }

    private static void OnGUI(int instanceID, Rect selectionRect)
    {
        var evt = Event.current;

        if (evt.type != event_last)
        { 
            switch (evt.type)
            {
                case EventType.DragExited:
                    OnHierarchyDragExit();
                    break;
            }
        }
        event_last = evt.type;
    }

    private static void OnHierarchyDragExit()
    {
        Object obj = UnityEditor.Selection.activeObject;
        System.Type type = (obj == null) ? null : obj.GetType();
        string path = AssetDatabase.GetAssetPath(obj);
        string name;

        {
            string[] array = path.Split('/');
            name = array[array.Length - 1];
            name = name.Split('.')[0];

            Debug.Log(string.Format("ドラッグ : {0} ({1})",name,type));
        }

        if (type == typeof(MonoScript))
        {
            foreach (MonoScript ms in mss)
            {
                var cls = ms.GetClass();

                if (cls != null && cls.Name == name)
                {
                    GameObject go = new GameObject();
                    go.name = name;

                    //if(go.AddComponent(name) == null)  //Unity4ならこっち
                    if (UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(go, "Assets/CustomHierarchy.cs (57,24)", name) == null)
                    {
                        GameObject.DestroyImmediate(go);
                    }
                    AssetDatabase.Refresh();
                }
            }

        }
    }

}
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.