Hint
Idle State is a great boilerplate to look at since it has little to no logic within it.
Boilerplate
Before we begin implementing any state logic, it’s important to lay the groundwork.
- Add your using statements (using UnityEngine; for example)
- Add the file to the namespace Momentum.States
- Make a new class within this namespace, that’s identical to the name of the file
Constructor
Next, add the constructor within the class you just created
In most cases, your constructor should look identical to the code above, where PlayerNewState is the name of the class.
The first part of the constructor, the parameters in () represent this classes’ constructor, and the part after the colon within the base() represent the super classes’ parameters. I would recommend that you use auto complete to generate these constructors since writing them out manually can get tricky. VS Code and Visual Studio have built in features to do this (as do most other IDE/Text Editors).
Override Methods
Now its time to add our Enter, Exit, LogicUpdate and PhysicsUpdate methods. Again, I would recommend having these auto generated.
Above is an example of an overriden method, where MethodName would be replaced by any of the methods in PlayerBaseState or the super class that have the virtual keyword. The virutal keyword, allows the method to be overriden in a sub class.
base.Method() calls the logic wrriten in the method of the super class to inherit the code.
Using Start() and Update()
In order to have some code called continously or once at the start of the game, you need access to Start() and Update(). to do this, make your method, then add it to the OnStartEvent and OnUpdateEvent.
Subscribe your Start method in the Player.cs, it’s important that you use the add equals symbol (+=) to add your method, instead of overwriting the entire list by using equals (=).
Then, if you need Update, subscribe it in the newly created Start method in your state. An example of this can be found in Dash State.
Adding Logic
LogicUpdate() runs only while this state is set as the current state in the State Machine. It is called in Update().
PhysicsUpdate() also runs only while this state is set as the current state, but is called in PhysicsUpdate().
Enter() is called once when this state is set as the current state.
Exit() is called once when transitioning to another state.
Transitions
Regarding transitions, they should almost always be in an if statement and run only if we aren’t exiting the state (!_isExitingState
); This is so we don’t transition more than once per state. Additionally, we can prevent them from running if the ability isn’t finished (!_isAbilityDone
) - only for sub states of the ability super state.