Using ApplyDamage in Unreal Engine 5 with C++

Let's use UE5's ApplyDamage function to broadcast a damage event to receiving actors.

Unreal Engine 5 first person shooter template shooting projectiles
FPS Template

Game Engine

Unreal Engine 5.5.3

IDE

Rider 2024.3.6

Project Name

MyProject

OS

macOS Sequoia 15.3.1

Unreal Engine 5 makes it readily available to deliver damage to any actor with the Gameplay Statics function ApplyDamage. The ApplyDamage function takes five parameters and if the other actor is setup to receive damage it'll trigger that actor's damage event.

Let's create a very simple example of applying damage. At the very least we need another actor to apply damage to and we can get that actor from a OnHit or OnBeginOverlap event (or anywhere applicable). Once we have a valid actor we can then pass in additional arguments where necessary. We'll pass in a damage value float, an instigator controller, a damage causer actor, and a damage class.

#include "Kismet/GameplayStatics.h"
...
void AMyProjectile::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
	if (IsValid(OtherActor))
	{
		AController* InstigatorController = GetInstigatorController();
		TSubclassOf<UDamageType> DamageType = UDamageType::StaticClass();
		
		UGameplayStatics::ApplyDamage(OtherActor, 100.f, InstigatorController, this, DamageType);
		Destroy();
	}
}

This is very simple example to get starter. DamageTypes and instigators can be very helpful, I write more about damage types in my DamageType post.

Comments (0)

Add a Comment

Sign in to comment or like.

Delete Comment

-