Repository shows simple idea on how to implement object drag in Unity(especially for games that make use of top down view). I've decided to make one because when my project needed something similiar, most of the Web results concerned mouse Drag&Drop functionality. However I succeed to find tip with gameObject.transform.parent. Making script to work flawlessly(without errors) took me some time but I think I got it. I used it for minigame puzzle. Here is the demo showing object drag in practice. Template project for this repository was made in Unity 2019.3.3f1 (64-bit).
In the repo you will find scene used to show the results, Slime Rabbit character, and some scripts. For the purpose of repo I extended drag with ability to rotate moved objects. It's used by Drag Handler and rotation is handled by script named Rotation Handler. Script containing only drag functionality is called raw_DragHandler. There is also short description on how to use it properly. Note on the picture below that, Movement Handler has bool variable called Dont Inherit Facing Direction.
What it means is that you can decide whether you want dragged objects to be positioned in front of the character when changing direction(inherit facing) or not(don't inherit facing). See the difference underneath:
Don't Inherit Facing | Inherit Facing |
---|---|
When looking at example with inherit facing, you probably noticed problem that the text also reacts on changing direction. To solve this for e.g. you can place on the draggable object script called Lock Rotation. See the result.
What about rotation? If you take a look again at the first image showing Unity inspector fragment, notice that Drag Handler script also comes with bool variable. This one let's you turn on and off rotation on dragged objects. If you keep variable checked, you will be able to rotate dragged object by using Left and Right arrow key. As before, check the outcome below.
Template generated using EzGitDoc