top of page

Extending the AGameMode Match State Machine

Updated: Mar 27, 2023

Today we will discuss extending the AGameMode class to include a custom state machine.


First, we need to create a new ACustomGameMode class that inherits from AGameMode. For the basic match-handling functionality, we will need to override the base class methods and also add our own.

ACustomGameMode.h
UCLASS()
class TUTORIALS_API ACustomGameMode : public AGameMode
{
	GENERATED_BODY()
	
protected:
	/// Override the AGameMode match functionality
	virtual void OnMatchStateSet() override;
	virtual void HandleMatchHasStarted() override;
	virtual void HandleMatchHasEnded() override;
	bool IsMatchInProgress() const override;

	/// Add our own states
	virtual void HandleMatchStateA();
	virtual void HandleMatchStateB();
};


In order to get more states, we will need to extend the MatchState namespace.

ACustomGameMode.h

/// Extending the MatchState namespace
namespace MatchState
{
	const FName StateA = FName(TEXT("StateA"));
	const FName StateB = FName(TEXT("StateB"));
}


The Implementation will be as follows:

ACustomGameMode.cpp

// This method is a callback to the SetMatchState method
void ACustomGameMode::OnMatchStateSet()
{
	// Handle our custom state A
	if (MatchState == MatchState::StateA)
	{
		HandleMatchStateA();
	}
	// Handle our custom state B
	else if (MatchState == MatchState::StateB)
	{
		HandleMatchStateB();
	}
	// Handle default AGameMode states
	else
	{
		Super::OnMatchStateSet();
	}
}

// this method is a callback to the StartMatch method
void ACustomGameMode::HandleMatchHasStarted()
{
	// Handle match has started
	Super::HandleMatchHasStarted();
}

// this method is a callback to the EndMatch method
void ACustomGameMode::HandleMatchHasEnded()
{
	// Handle match has ended
	Super::HandleMatchHasEnded();
}

// Mark our states as part of the match is in progress
bool ACustomGameMode::IsMatchInProgress() const
{
	if (GetMatchState() == MatchState::StateA ||
		GetMatchState() == MatchState::StateB)
	{
		return true;
	}
	else
	{
		// Other states are handles by the AGameMode class
		return Super::IsMatchInProgress();
	}
}

// Our custom state functionality after moving to state A
void ACustomGameMode::HandleMatchStateA()
{
	// Example handling state A  by moving straight to state B
	SetMatchState(MatchState::StateB);
}

// Our custom state functionality after moving to state B
void ACustomGameMode::HandleMatchStateB()
{
	// Handle state B
}

By implementing all the above functionality, you should be able to create and extend the match state machine to your needs.


A similar logic can be added to the GameState class by overriding the corresponding methods.


Please let us know if you have any questions.

Comments


bottom of page