Using an Integer instead of Booleans for current states

Hey guys, I’ve been working on my player’s script, and was wondering if using one integer to handle actions rather than a Boolean for every action would work better in terms of performance, or it would it be negligent?

I ask now because I don’t want to finish the whole thing only to find out one way is better than the other.

for example:

private bool jump;
private bool climb;
private bool dead;

I could instead do:

private int action=0;

And then define the int as 1, 2, 3 etc. to say if action == 2 then we’re climbing.

You can do this, but I have no idea why you would, using booleans is a lot more understandable to me >.<

Integers are far better, since you only test the movement state in a switch rather than checking each boolean and trying to determine which to check for first.

But you can look beyond integers too and check out state machines. Here’s an example for AI: https://unity3d.com/learn/tutorials/topics/scripting/using-interfaces-make-state-machine-ai

It also translates to player movement, as it makes it simple to accept only the input you need for that state, instead of having a bunch of conditional statements for all the edge cases. If you’re in the falling state, only check for the parachute button and make that transition to the floating state, for example. The logic will be nicely grouped with each state, and the code gets easier to read. Out of sight, out of mind is very true when the code stretches past one visible screenful of text :slight_smile:

1 Like

Awesome, I had no idea about state machines, that about does it, thanks orb, thank you Rob.

also if your usecase dosnt need a full state machine you can use a Enum works like a int, but is named so things are more readable. they work really well if you use a enum in a switch statemeant

3 Likes