I finished watching a couple tutorials on state machines in unity and I'm now trying to figure out how I can actually use one with my player movement code, but I'm a bit stuck. The tutorial I followed had shown to do a StateManager script like this
public class PlayerStateManager : MonoBehaviour
{
PlayerBaseState currentState;
public PlayerJumpState jumpState = new PlayerJumpState();
public PlayerIdleState idleState = new PlayerIdleState();
public PlayerRunState runState = new PlayerRunState();
void Start()
{
currentState = idleState;
currentState.EnterState(this);
}
void Update()
{
currentState.UpdateState(this);
}
public void SwitchState(PlayerBaseState state)
{
currentState = state;
state.EnterState(this);
}
}
And now I assumed all I would need to do to use this was this
public class TestMovement : MonoBehaviour
{
PlayerStateManager playerState;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
playerState.SwitchState(playerState.jumpState);
}
}
}
But this clearly isn't correct since I keep getting an error saying "NullReferenceException: Object reference not set to an instance of an object" at the line with SwitchState.
CodePudding user response:
In TestMovement
, do you have a Start
or Awake
method which assigns something to the playerState
field? If not, that field is never assigned and is therefore always null.
Another thing you could do is make it public PlayerStateManager playerState;
and assign something to it in the editor.
CodePudding user response:
playerState is private by default so you have to make public or [SerializeField] and introduce it in the game engine