When it comes to making a player controller in Unity, there are many ways to structure it depending on the complexity of your game. Making a simple mobile game? A player controller within a single class will probably get the job done. Making a platformer with a diverse moveset? Then putting everything into one class can get messy really fast.

One approach to solve this problem is a programming pattern called Finite-State-Machine. A gameObject with a Finite-State-Machine can have a finite number of states as the name suggests, but it can only be in a single active state at a time. Examples for states are walking, jumping and dashing. Each of these different states needs to run different code because the character has different abilities in each state.

This programming pattern is often used in games for AIs. Things like enemies that can be in a patrol-state and a chase-state and such. But it’s also possible to use it for player controllers.

The way I do it is to separate the abilities of the character (jump, move horizontal, shoot), which are classes themselves, from the state machine. Therefore, the only thing the state machine has to do is to enable and disable the ability-scripts. For example, you want the jump-ability to be disabled while the gameObject is in the air.

Here are some helpful links if you need to implement a finite state machine in your game:

http://gameprogrammingpatterns.com/state.html

https://unity3d.college/2017/05/26/unity3d-design-patterns-state-basic-state-machine/

Categories: Uncategorised