Hello
I want to implement an undo button where if the player drags an object and drops it anywhere and wants to bring it back to its original position, they can use the undo button. I have already made a script for dragging and dropping game objects but I don’t know how to undo them. Any help is appreciated.
Unless there are other variables that are changed as a result of the drag, all you need to do is store the starting position in the OnMouseDown method. When you undo, move the game object back to the original position. If you have events triggered or other variables changed or other callbacks (OnCollision or OnTriggerEnter, for example), it gets more complex and you potentially have to undo rather a lot of changes.
You might wonder how this is done in games development or how an undo history works in productivity tools or, for example, how does a race replay work at the end of a racing game. They use what is called the Command Pattern, where every input is stored in a list. The main part of the Update routine is simply collecting all these inputs and adding them to the list. Then there are matching forward and backward functions to process each of these inputs. Forward for normal processing and the replay function; backward for single or multiple undos. There is always a list of every input that the user made - each press of a button on the keyboard, every wiggle of the joystick etc. The entire game can be replayed or wound back.
void OnMouseDown()
{
// store your old position in a vector 3
_oldPosition = yourObjectsPosition;
}
// Set up your undo button OnClick to move your object back to old position
public void OnButtonPress()
{
yourObjectsPosition = _oldPosition;
}
Do you just have a single object that is dragged? If so, you should use a Stack to store successive positions. Stacks can store data of a fixed type in a way that if you “push” onto the stack, the value goes on the top. Then if you ‘pop’, you get the last item that was put onto the stack.
So, when you start a drag (possibly when you get MouseDown), push the transform.position onto the stack. When you undo, you pop from the stack and set the transform position.
Just one more thing, if you try and pop from an empty stack, you’ll get an error so there’s a little trick that checks first.
All this code should sit on your draggable object. The Undo button should point at the Undo method. Do you fancy getting cute? If so, disable the Undo button when the stack is empty. You can use undoData.count to tell you how many items there are in the stack.
Check out the command pattern! It’s a very powerful programming pattern and one of it’s most common uses is to create undo/redo systems, surprised no one mentioned it yet… You define actions as commands and then can create a history of commands by storing them in a list.