- Home /
The question is answered, right answer was accepted
Custom Editor: How to get a reference to an existing object in the scene at the mouse position after drag-and-dropping a prefab into the scene?
This is what I'm trying to accomplish: On drag-and-dropping a prefab into the scene, if another object with the same tag exists at that position (this is a 2D scene, mind you), delete it and replace it with the new object (keeping the old object's position in the scene and the hierarchy).
The part I'm having a problem with is checking if any existing objects are at the drop position and getting a reference to them, and after a couple hours of googling and going through the manual I'm still stumped.
[CustomEditor(typeof(CommonTile))]
public class CommonTileInspector : Editor
{
void OnSceneGUI()
{
if (Event.current.type == EventType.DragExited)
{
GameObject oldObj = this.getObjectAtDropPosition();
GameObject newObj = ((CommonTile)this.target).gameObject;
if (oldObj != null && oldObj.CompareTag(newObj.tag))
{
newObj.transform.SetParent(oldObj.transform.parent);
newObj.transform.position = oldObj.transform.position;
Undo.DestroyObjectImmediate(oldObj);
}
Event.current.Use();
}
}
private GameObject getObjectAtDropPosition()
{
// this is the part that stumps me
}
}
HandleUtility's PickGameObject and PickRectObjects functions look promising, but I can't figure out how to get a mouse position at this point; getting Event.current.mousePosition just gives me the same negative numbers regardless of where I drop the object (likely related to the object not actually existing in the scene until after it's been dropped).
Answer by Commoble · Feb 22, 2017 at 06:39 AM
Well, nevermind, I figured it out. Use the new object's transform to get a worldspace rect around that object, and convert it to screen space via the current camera.
Only problem is Undo.DeleteObjectImmediate doesn't delete the old object (and using plain ol' Object.DeleteImmediate doesn't register an undo by itself), but that's a separate problem and I'll make a separate question if it keeps bothering me. Gonna close this one.
Follow this Question
Related Questions
[Editor] Get Scroll Wheel while dragging 0 Answers
Editor-only circular contour around prefab instances 2 Answers
Editor: calling event.use() prevents gizmos from being drawn 1 Answer
Why animation events do not change sprite position? 1 Answer
How to execute a script each time I add a certain prefab to the scene? 2 Answers