private int i;
Start()
{
// determine if i should be 0, 1, 2, or 3
}
Update()
{
if ( i == 0)
{
// do something
}
if(i == 1)
{
// do something else
}
if(i == 2)
{
// do something else
}
if(i == 3)
{
// do something else
}
}
Obviously, this is bad for performance; since the value of i will never change, 3/4 of the highest-level checks in the update function are useless at any given time. How can I make it so that the start function determines which code is run during Update()?
There is absolutely nothing wrong with doing those IF tests, except that you should be using ELSE to prevent unecessary condition tests of i once a true condition is met. For example I’ve modified your code here:
Update()
{
if ( i == 0)
{
// do something
}
else if(i == 1)
{
// do something else
}
else if(i == 2)
{
// do something else
}
else if(i == 3)
{
// do something else
}
}
You can further optimize by making the order of your IF tests based on which value is most likely to be true. Then it will run through less IFs. (But really, the performance impact is negligible unless you have hundreds)
I would declare an enum before Start(). Like GameState:
public enum GameState {
Loading,
Playing,
Paused,
None
};
You can then create a state variable:
GameState state = GameState.None;
You can set it to whatever enum value you want in start.
void Start() {
state = GameState.Loading;
}
After that you have a switch statement in Update that will do different things based off of which GameState state is set to.
void Update() {
switch(state) {
case GameState.Loading:
// do loading things
break;
case GameState.Playing:
// do playing things
break;
case GameState.Paused:
// do paused things
break;
case GameState.None:
// do nothings
break;
default:
// default is a catch-all in case the state is set to something weird
break;
}
}
From there you need to come up with conditions as to what will cause the state variable to be changed in the different steps (user presses the pause button while it is in the “Playing” state, so we change state to “Paused”).