DragAndDrop - Get Instantiated Object and other info

Hi,

When you click a prefab in the Project Window and drag it into the scene it will Instantiate that prefab and place it into the hierarchy. Is it possibly, and if so how, to get the object that object(s) created from the dragging and dropping.

I could record the root items of the scene when:UnityEngine.Event.current.type == EventType.DragPerform
wait a frame and compare which ones have been added. However I would have thought there would be a nicer way to get the object created from DragAndDrop

After lots of digging, I finally found a way to do this. Sort of. I’m not sure if you can get the created object, but you can intercept the creation of it and manipulate it as you wish.

First thing you need to do is subscribe to the onSceneGUIDelegate

//Some init
        SceneView.onSceneGUIDelegate += SceneViewDragAndDrop;
 private void SceneViewDragAndDrop(SceneView sceneView)
    {
        var current = UnityEngine.Event.current;
        var references = DragAndDrop.objectReferences;
        if (current.type == EventType.Repaint || current.type == EventType.Layout) return;
        if (references.Length > 0 && UnityEngine.Event.current.type == EventType.DragPerform)//only check relevant drops
        {
            var obj = GameObject.Instantiate(references[0]);//this example only handles one drop
            var go = (GameObject) GetHidenType(typeof(Editor), "GameObjectInspector").GetField("dragObject").GetValue(null); //Reflect to get the GameObjectInspector  
            if (go)
            {
                ((GameObject)obj).transform.position = go.transform.position;
                current.Use(); // don't let the 
            }
        }
    }
    public static System.Type GetHidenType(System.Type aBaseClass, string TypeName)
    {
        System.Reflection.Assembly[] AS = System.AppDomain.CurrentDomain.GetAssemblies();
        foreach (var A in AS)
        {
            System.Type[] types = A.GetTypes();
            foreach (var T in types)
            {
                if (T.IsSubclassOf(aBaseClass) && T.Name == TypeName)
                    return T;
            }
        }
        return null;
    }

GO is the preview object you see in the scene. Setting the current event to use will block creation of go, hence me instantiating the referenced gameobject.

The refelctioney bit can be done better (i.e. store the fieldinfo on init), but this was a quick example.
I ripped GetHidenType off someone on the internet, you have to do this because you don’t have access to where the dragged gameobject is stored :frowning:

1 Like

Is this actually working? GameObjectInspector doesn’t has a field called dragObject (it’s called m_DragObject now), yet it requires an object reference to call for GetValue(). You put null there, but the m_DragObject variable is not a static variable.

Have you found the solution now? Thanks in advance!