How to tell if the code flow changed
Alright, so this is something I've never quite figured out how to do efficiently.
You could have:
bool last;
//true = was last in the if statement
//false = was last in the else statement
if (/*not important*/)
{
if (!last)
//Special code
last = true;
//Normal Logic
}
else
{
if (last)
//Special code
last = false;
//Normal Logic
}
This is a technique that I've always used to circumvent this problem, but I was just wondering if there was a more efficient way of doing this.
The situation I'm dealing with now is I want to switch between two different camera positions and be able to tell WHEN it switches modes. If I know when it switched, I'll use some special code to lerp it to the correct position.
I'm sure I could use this method or something similar, but I just wanted to minimize my use of variables.
Thanks if anyone can help!
The alternative is effectively a state machine. If you lookup a simple state machine example you can see how they can be easily used to represent any number of states and a clean way of handling transitions to said states. Also, having code run when you enter or leave those states.
Overkill for two states I suppose.
Just food for thought.
Thanks so much. Doing a lot of research in that area now. I've always heard of that area of logic, but I never got its purpose and functionality until now. Definitely moving in the right direction now, thanks :)
Answer by JustJunuh · Jan 09, 2017 at 07:43 PM
Once again, I show just how noobish I really am to coding. Basically the solution I was looking for is found in FSM.
Anyone who wants to learn more can follow these links: http://gameprogrammingpatterns.com/state.html https://www.youtube.com/watch?v=hhByGZZbcOc
Answer by UnityCoach · Jan 09, 2017 at 09:25 PM
If all you need is to know when a bool value changed, you can simply use a property (variable + accessor), like :
private bool _state;
public bool State
{
get { return _state; }
set
{
if (value != _state) // is value changed
{
// do whatever based on old value
_state = value; // assign new value to variable
// do whatever based on new value
}
}
}
Interesting. I'll see what I can make of that. $$anonymous$$y whole question is pretty open ended and I was more asking for future techniques that I could use to improve my code. I'll definitely keep this one in the back of my $$anonymous$$d. Thanks :)
Actually, it works with any type, you can even add an event in it, so that other classes can subscribe to this value change, like :
public enum STATE {Initialising, Ready, Starting, Started, Running, Stopping, Stopped};
public delegate void StateChange(STATE state) ;
public event StateChange StateChanged;
private STATE _state;
public STATE State
{
get { return _state; }
set
{
if (value != _state)
{
_state = value;
if (StateChanged != null)
StateChanged(_state);
}
}
}