2 min read

Assign player team on spawn

Assign player team on spawn
Photo by Markus Spiske / Unsplash

Gameplay Tags

Unreal Engine has this great generic system for storing arbitrary labels called Gameplay Tags. It’s essentially FNames with some special handling in the engine and editor. It allows us to label things in various ways without risking user error when typing strings both in code and in the editor. We will use this to set up a team system and assign a team to a player when they spawn.

Custom spawn point

To be able to assign a tag to the player when they spawn, we first need to tag the spawn point itself with a tag. We do this by creating a new class deriving from APlayerStart and exposing a tag we can fill in the editor.

UCLASS()
class MY_API AMyPlayerStart : public APlayerStart
{
	GENERATED_BODY()

public:
	const FGameplayTag& GetTeamTag() const { return TeamTag; }
	
protected:
	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Tags")
	FGameplayTag TeamTag;
};

In the editor we then create a Blueprint Class deriving from our new MyPlayerStart and set a new tag on it called Team.Red. We can create a duplicate and add a tag Team.Blue. This gives us two spawn point Blueprints we can use for the two teams.

Assigning the team to players

To assign the team tag from the spawn point to the player we need a custom gamemode class. We create one derived from AGameModeBase and make sure to set it up in the editor for the project to use it. For the actual assignment of the tag we need to override a single function that will be called once a player spawns at a spawn point.

UCLASS()
class MY_API AMyGameModeBase : public AGameModeBase
{
	GENERATED_BODY()
	
public:
	void InitStartSpot_Implementation(AActor* StartSpot, AController* NewPlayer) override;
};

MyGameModeBase.h

void AMyGameModeBase::InitStartSpot_Implementation(AActor* StartSpot, AController* NewPlayer)
{
	// call parent class to run original logic
	Super::InitStartSpot_Implementation(StartSpot, NewPlayer);

	// probably unnecessary to check all these pointers but better safe...
	if (!NewPlayer)
	{
		return;
	}

	AMyPlayerStart* PlayerStart = Cast<AMyPlayerStart>(StartSpot);
	if (!PlayerStart)
	{
		return;
	}

	// depending on where you keep the player team tag, you just access that location and set it here. in this example we have it on our custom character class
	AMyCharacter* Character = Cast<AMyCharacter>(NewPlayer->GetCharacter());
	if (!Character)
	{
		return;
	}
	
	Character->SetTeamTag(PlayerStart->GetTeamTag());
}

MyGameModeBase.cpp

Now we have a team tag on our character set to different values depending on what spawn point is used for that character. You can use this to detect friendly fire, increase kills for the right team, and anything else you might need it for.