Skip to main content

07 - Data-Driven Weapon

The classic data-driven pattern: a USTRUCT holds tuning, an actor exposes it, and a derived function computes damage-per-second.

Full source​

include "CoreMinimal.h"
include "GameFramework/Actor.h"

ustruct FWeaponStats (BlueprintType)
{
prop public int32 Damage default=10
prop public float FireRate default=1.0f
prop public FName Tag default="Default"
}

uclass AExampleWeapon : AActor meta: api=EXAMPLES_API
{
prop public FWeaponStats Stats EditAnywhere BlueprintReadWrite category="Example"

method public virtual void BeginPlay() override {
Super::BeginPlay();
UE_LOG(LogTemp, Warning, TEXT("Weapon %s DPS = %.1f"), *Stats.Tag.ToString(), DamagePerSecond());
}

func public float DamagePerSecond() BlueprintCallable category="Example"
{
return Stats.FireRate > 0.0f ? (float)Stats.Damage / Stats.FireRate : 0.0f;
}
}

Line by line​

  • ustruct FWeaponStats (BlueprintType) - a USTRUCT exposed as BlueprintType so it appears as a struct type in Blueprints.
  • prop public int32 Damage default=10 / prop public float FireRate default=1.0f / prop public FName Tag default="Default" - struct fields, all public for BP access.
  • prop public FWeaponStats Stats EditAnywhere BlueprintReadWrite - an actor property holding the struct. Editing Stats.Damage etc. in the Details panel updates the whole container at once.
  • func public float DamagePerSecond() BlueprintCallable - computes DPS from the struct: Damage / FireRate, guarding against divide-by-zero.
  • BeginPlay - logs the tag and computed DPS.

Why data structs win​

  • Grouping - related tuning travels together instead of a pile of scalars.
  • Serialization - the struct is one property for save/load.
  • Reuse - the same FWeaponStats can back a weapon, a trap, a skills table, etc.
  • Designer-friendly - exposes one tidy block in the Details panel and as a struct in Blueprint.

Pattern value​

Use a ustruct whenever a mechanic has a cluster of numeric/label fields. See USTRUCT, UENUM & Interfaces.

Next: 08 - Interfaces.