LoginSignup
0
0

More than 5 years have passed since last update.

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

Posted at

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();
                }
            }

        }
    }

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0