- Home /
Save previous Enum variable in Update
I am trying to create a method that remembers the previous variable value.
I have the following:
enum Direction { UP, DOWN, LEFT, RIGHT, NONE };
Direction myDirection;
Direction previousDirection;
private void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
myDirection = Direction.UP;
}
if (Input.GetKeyDown(KeyCode.A))
{
myDirection = Direction.LEFT;
}
if (Input.GetKeyDown(KeyCode.S))
{
myDirection = Direction.DOWN;
}
if (Input.GetKeyDown(KeyCode.D))
{
myDirection = Direction.RIGHT;
}
Now I want every time myDirecition changes, the previous state to be remembered in previousDirection
Comment
Best Answer
Answer by Bunny83 · May 31, 2019 at 09:21 AM
Just do:
void SetDirection(Direction aNewDir)
{
previousDirection = myDirection;
myDirection = aNewDir;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
SetDirection(Direction.UP);
}
if (Input.GetKeyDown(KeyCode.A))
{
SetDirection(Direction.LEFT);
}
if (Input.GetKeyDown(KeyCode.S))
{
SetDirection(Direction.DOWN);
}
if (Input.GetKeyDown(KeyCode.D))
{
SetDirection(Direction.RIGHT);
}
}
If you want to prevent the previousDirection to change when the same key is pressed multiple times in a row, just change SetDirection to:
void SetDirection(Direction aNewDir)
{
if (aNewDir != myDirection)
previousDirection = myDirection;
myDirection = aNewDir;
}
That should work. Boy do I feel bad now. How simple it was and here I am 2 hours straight thinking. I should go get a coffee.
Your answer
Follow this Question
Related Questions
Change Inspector Variables Depending On Enum 2 Answers
how to transport a selection from scene to scene 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers