Hello guys, for a whole day I have been struggling with one error and everything seems fine to me. I can’t explain why this is happening. I will post the simplified version of my code, but first here are some details about my setup.
My classes:
- APlayerCharacter - inherits from ACharacter.
- FCharacterState - an abstract normal C++ class (Doesn’t inherit from any special UE4 classes).
- FIdleState - another normal class that inherits from FCharacterState.
- FCharacterStateMachine - It contains instances of FCharacterState and is contained in APlayerCharacter.
Here are all my classes, but with only relevant data in the order above:
APlayerCharacter.h:
UCLASS()
class LEARNINGGROUND_API APlayerCharacter : public ACharacter
{
GENERATED_BODY()
public:
APlayerCharacter();
// Other class methods.
private:
FCharacterStateMachine StateMachine;
// Other members
};
APlayerCharacter.cpp :
APlayerCharacter::APlayerCharacter()
{
PrimaryActorTick.bCanEverTick = true;
this->StateMachine = FCharacterStateMachine(this);
}
void APlayerCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// This code cause the error.
this->StateMachine.UpdateCurrentState();
}
Here is the CharacterStateMachine constructor:
FCharacterStateMachine::FCharacterStateMachine(APlayerCharacter* Character)
{
this->IdleState = FIdleState(this);
this->CurrentState = &(this->IdleState);
}
And finaly the method that causes the error:
void FCharacterStateMachine::UpdateCurrentState()
{
if (this->CurrentState != nullptr)
{
this->CurrentState->Update();
}
}
When debugging It enters the body of the if statement, in other words CurrentState != nullptr , but it doesn’t enter the Update method, before entering the Update I get this error:
Exception thrown at 0x000000A4CDACC480 in UE4Editor.exe: 0xC0000005: Access violation executing location 0x000000A4CDACC480. occurred
I have no clue what seems to be the problem. It seems that everything initializes correctly. My first guess was null reference exception, but since everything seems to be initialized correctly it appears it’s not the case.
EDIT: Here is the FCharacterStateMachine.h
class LEARNINGGROUND_API FCharacterStateMachine
{
public:
FIdleState IdleState;
FWalkingState WalkingState;
FJoggingState JoggingState;
FCharacterStateMachine();
FCharacterStateMachine(APlayerCharacter* Character);
void UpdateCurrentState();
APlayerCharacter* GetCharacter() const;
FCharacterState* GetCurrentState() const;
void SetCurrentState(FCharacterState& State);
FCharacterState* GetPreviousState() const;
void SetPreviousState(FCharacterState& State);
private:
APlayerCharacter* Character;
FCharacterState* CurrentState;
FCharacterState* PreviousState;
};