takashiskiのブログ

覚書の殴り書き

UIでDrag&Dropをする、のメモ

うんうん悩んでやっとわかった気がしたのでメモ。

Drag

  • CanvasGroupをもたせる
  • CanvasGroup.blockRaycastsを開始時にfalse、終了時にtrueにする
  • IBeginDragHandler,IEndDragHandler,IDragHandlerを継承する
  • OnBeginDragで親オブジェクトを退避する
  • OnEndDragで退避していた親オブジェクトを親オブジェクトに設定しなおす
  • OnDragではマウスポインタに追従させる処理をする

Drop

  • IDropHandlerを継承する
  • eventData.PointerDragでDropされたオブジェクトを取得可能
  • 直接parentを編集することもできるが、RectTransformの親を外からSetParentでいじることはよくないらしい*1ので、Draggableなクラスであれば退避されている親を書き換える。そうでなければなにもしない

参考記事

最終的に最後の記事の内容がよさそうだと思った。

komekkun.com

qiita.com

qiita.com

*1:Parent of RectTransform is being set with parent property. Consider using the SetParent method instead, with the worldPositionStays argument set to false. This will retain local orientation and scale rather than world orientation and scale, which can prevent common UI scaling issues.