Search Unity

Dragging Scriptable Object into scene

Discussion in 'Scripting' started by BinaryCats, Feb 15, 2018.

  1. BinaryCats

    BinaryCats

    Joined:
    Feb 8, 2016
    Posts:
    317
    Hi,

    I am trying to add support for drag and drop a scriptable object into a scene. upon drop, the drag action should instantiate which ever Item the Scriptable Object asset is referring too. I want to mimic the prefab behaviour of the object snapping to objects in the scene.

    Code (csharp):
    1.  
    2. private static void SceneViewDragAndDrop(SceneView sceneView)
    3.     {
    4.         var current = Event.current;
    5.         if (current.type == EventType.Repaint || current.type == EventType.Layout) return;
    6.         if (UnityEngine.Event.current.type == EventType.DragPerform)
    7.         {
    8.             if (CachedObject)
    9.             {
    10.                 CachedObject.hideFlags = HideFlags.None;
    11.                 Selection.activeObject = CachedObject;
    12.                 CachedObject = null;
    13.                 return;
    14.             }
    15.         }
    16.         var references = DragAndDrop.objectReferences;
    17.         if (references.Length > 0 && UnityEngine.Event.current.type == EventType.DragUpdated)//only check relevant drops
    18.         {
    19.             var item = references[0] as BaseItemDataContainer;
    20.             if (item && CachedObject == null)
    21.             {
    22.                 DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
    23.                 CachedObject = GameObject.Instantiate(item.m_Item.gameObject);
    24.                 CachedObject.hideFlags = HideFlags.HideInHierarchy;
    25.                 F_DragObject.SetValue(null, CachedObject);
    26.                 F_IgnoreRayCast.SetValue(null, CachedObject.GetComponentsInChildren<Transform>());
    27.                 DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
    28.             }
    29.         }
    30.     }
    31.  
    where SceneViewDragAndDrop is subscribed to SceneView.onSceneGUIDelegate
    And F_DragObject is a reflected fieldinfo of the hidden class GameObjectInspector.cs

    I Have used this method on prefabs before, altering the object that is dragged from the project window, which works. but this method doesn't seem to work for scriptable objects, as the object doesn't follow the cursor and DragPerformed never gets called.

    Does anybody know a solution or another method of setting which object is being dragged into scene?

    Thanks