Common Snippets In C++

It can be hard to look for what you don't know. This page will contain common code snippets/function signatures for commonly asked about C++ scenarios. Ideally these should link off to pages with m...

Updated almost 4 years ago Edit Page Revisions

It can be hard to look for what you don't know. This page will contain common code snippets/function signatures for commonly asked about C++ scenarios. Ideally these should link off to pages with more advanced examples as needed.

Unreal MACROs

UCLASS

Declaration of the most basic UCLASS

// .h
UCLASS()
class PROJECTNAME_API MyClassName : public ParentClass
{
    GENERATED_BODY()
public:
    MyClassName();
protected:
private:
};

USTRUCT

Declaration of the most basic USTRUCTs

USTRUCT(BlueprintType)
struct FMyStruct
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=MyCategory)
    float MyFloat;
};

MyStruct that can be used for a DataTable:

USTRUCT(BlueprintType)
struct FMyStruct : public FTableRowBase
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=MyCategory)
    float test;
};

UENUM

Declaration of the most basic UENUM

UENUM(BlueprintType)
enum class EMyMovementStatus : uint8
{
    Idle UMETA(DisplayName="Idle"),
    Walking UMETA(DisplayName="Walking"),
    Running UMETA(DisplayName="Running")
};

UFUNCTION

Basic UFUNCTION

UFUNCTION()
void MyFunctionName();

UFUNCTION()
void MyFunctionNameWithParameters(const FString& SomeString, int SomeInt);

UFUNCTION with networking

Declaration(.h) for AMyActorClass

UFUNCTION(Client, Unreliable)
void MyFunctionName();

UFUNCTION(Client, Unreliable)
void MyFunctionNameWithParameters(const FString& SomeString, int SomeInt);

UFUNCTION(NetMulticast, Reliable, WithValidation)
void MyMulticastFunctionName();
//
UFUNCTION(Server, Reliable, WithValidation)
void MyServerFunctionName(FRotator Rotation);

Implementation(.cpp) of AMyActorClass

void AMyActorClass::MyFunctionName() {}

void AMyActorClass::MyFunctionNameWithParameters(const FString& SomeString, int SomeInt) {}

void AMyActorClass::MyMulticastFunctionName() {}
bool AMyActorClass::MyMulticastFunctionName_Validate() { return true; }
void AMyActorClass::MyMulticastFunctionName_Implementation() {}

void AMyActorClass::MyServerFunctionName(FRotator Rotation) {} 
bool AMyActorClass::MyServerFunctionName_Validate(FRotator Rotation) { return true; }
void AMyActorClass::MyServerFunctionName_Implementation(FRotator Rotation) {}

UINTERFACE

Basic example of header of UINTERFACE

UINTERFACE()
class TASGAME_API UInteractable: public UInterface
{
    GENERATED_BODY()
};

class IInteractable
{
    GENERATED_BODY()
public:
    UFUNCTION(Category = "Interactable")
    virtual bool CanInteract();
    UFUNCTION(Category = "Interactable")
    virtual void PerformInteract();
};

Components

Creating a spring arm and camera

Creating a camera component from inside an actor constructor

// .h
    UPROPERTY(VisibleAnywhere)
    USpringArmComponent* m_springArmComponent = nullptr;
    UPROPERTY(VisibleAnywhere)
    UCameraComponent* CameraComponent = nullptr;
// .cpp
    SpringArmComponent = CreateDefaultSubobject(FName("SpringArmComponent"));
    m_springArmComponent->SetupAttachment(RootComponent);
    SpringArmComponent ->TargetArmLength = 1000;

    CameraComponent = CreateDefaultSubobject(FName("CameraComponent"));
    CameraComponent->SetupAttachment(SpringArmComponent);

Overlapping Collision Components

An Actor Component overlap binding

// UShapeComponent* TriggerShapeCollisionComponent 
TriggerShapeCollisionComponent->OnComponentBeginOverlap.AddDynamic(this, &UMyComponent::OnOverlapBegin);
TriggerShapeCollisionComponent->OnComponentEndOverlap.AddDynamic(this, &UMyComponent::OnOverlapEnd);
...
    UFUNCTION()
    void OnOverlapBegin(UPrimitiveComponent* OverlappedComponent,
        AActor* OtherActor,
        UPrimitiveComponent* OtherComp,
        int32 OtherBodyIndex,
        bool bFromSweep,
        const FHitResult& SweepResult);

    UFUNCTION()
    void OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);

An actor overlap binding

OnActorBeginOverlap.AddDynamic(this, &UMyActor::OnActorBeginOverlap);
OnActorEndOverlap.AddDynamic(this, &UMyActor::OnActorEndOverlap);
...
    UFUNCTION()
    void OnActorBeginOverlap(AActor* OverlappedActor, AActor* OtherActor);
    UFUNCTION()
    void OnActorEndOverlap(AActor* OverlappedActor, AActor*, AActor* OtherActor);

Misc

Logging

GEngine->AddOnScreenDebugMessage(0, 0.f, FColor::Red, FString::Printf(TEXT("TEXT")));
// Simple
UE_LOG(LogTemp, Display, TEXT("Your message"));
// With Formatting 
// (const TCHAR* Message, int64 SomeInt)
UE_LOG(LogTemp, Display, TEXT("Your message string %s with a number %d"), Message, SomeInt);
// (const FString& Message, float SomeFloat)
UE_LOG(LogTemp, Display, TEXT("Your message string %s with a number %f"), *Message, SomeFloat);
// (const FName& Message, bool SomeBool)
UE_LOG(LogTemp, Display, TEXT("Your message string %s with a bool %d"), *Message.ToString(), SomeBool);

Getting Things

Get all actors (warning: Expensive operation)

// TArray ActorArray; FName SearchTag; ...
UGameplayStatics::GetAllActorsOfClass(GetWorld(), AMyClass::StaticClass(), ActorArray);
UGameplayStatics::GetAllActorsWithTag(GetWorld(), SearchTag, ActorArray)
UGameplayStatics::GetAllActorsOfClassWithTag(GetWorld(), APlayerCharacterBase::StaticClass(), SearchTag, ActorArray)

Get a component from inside an Actor

UActorComponent* myComponent = GetComponentByClass(USomeActorComponent::StaticClass());

Get a component with casting from inside an Actor

USomeActorComponent* myComponent = Cast(GetComponentByClass(USomeActorComponent::StaticClass()));

Get all components from inside an Actor

TSet myComponents = GetComponents();
TArray components = GetComponentsByTag(UActorComponent::StaticClass(), SearchTag);
TArray components = GetComponentsByInterface(UMyInterface::StaticClass());

Input

InputComponent->BindAction("Button", EInputEvent::IE_Pressed, this, &MyClass::ButtonPressed);
...
void MyClass::ButtonPressed() {}
InputComponent->BindAxis("MoveForward", this, &MyClass::MoveForward);
...
void MyClass::MoveForward(float axisValue)

Saving

Saving a game to be later loaded in. Create a class that inherits from USaveGame. Add some member property, such as `float HighScore`

UMySaveGame* Instance = Cast(UGameplayStatics::CreateSaveGameObject(UMySaveGame::StaticClass()));
Instance.HighScore = 100;
UGameplayStatics::SaveGameToSlot(Instance, SaveSlotName, UserIndex);

Load from the save and set appropriate value.

UMySaveGame* Instance = Cast(UGameplayStatics::LoadGameFromSlot(SaveSlotName, UserIndex));
MyGameInstance.HighScore = Instance.HighScore;

Spawning Actors

An actor is the base class that can be placed or spawned into a world. See Actor

Simple spawning actors into the world:

// (FVector Location, FRotator Rotation)
AMyClass* ActorName = GetWorld()->SpawnActor(Location, Rotation);

Deferring a spawned actor, allows you to delay the actual spawning of the object and thus the BeginPlay will be deferred on this actor. This would allow you to make a change after construction but before BeginPlay occurs.

// Called to get an instance to the constructed actor
AMyClass* ActorName = GetWorld()->SpawnActorDeferred(UClass, ActorTransform, Owner, Instigator, ESpawnActorCollisionHandlingMethod::AlwaysSpawn);
// Do some stuff
...
// Needs to be called to actually finish and have BeginPlay start on the given Actor
UGameplayStatics::FinishSpawningActor(ActorName, ActorTransform);

Audio

There is a large variety of dialog and sound you can spawn and play.

If you want to do a fire and forget sound, you should use the PlaySound functions instead of the spawn ones.

Spawn dialogue 2D:

UAudioComponent* MyDialog = UGameplayStatics::SpawnDialogue2D(GetWorld(), DialogWave, DialogContext, VolumeMultiplier, PitchMultiplier, StartTime, bAutoDestroy);

Spawn dialogue attached:

UAudioComponent* MyDialog = UGameplayStatics::SpawnDialogueAttached(GetWorld(), DialogWave, DialogContext, AttachToComponent, AttachPointName, Location, Rotation, EAttachLocation::KeepRelativeOffset, bStopWhenAttachedToDestroyed, VolumeMultiplier, PitchMultiplier, StartTime, Attenuation, bAutoDestroy);

Spawn dialogue at location:

UAudioComponent* MyDialog = UGameplayStatics::SpawnDialogueAtLocation(GetWorld(), DialogWave, DialogContext, Location, Rotation, VolumeMultiplier, PitchMultiplier, StartTime, Attenuation, bAutoDestroy);

Spawn sound 2d:

UAudioComponent* MySound = UGameplayStatics::SpawnSound2D(GetWorld(), SoundBase, VolumeMultiplier, PitchMultiplier, StartTime, Concurrency, bPersistentAcrossLevelTransition, bAutoDestroy);

Spawn sound attached:

UAudioComponent* MySound = UGameplayStatics::SpawnSoundAttached(SoundBase, AttachToComponent, AttachPointName, Location, Rotation, EAttachLocation::KeepRelativeOffset, bStopWhenAttachedToDestroyed, VolumeMultipler, PitchMultiplier, StartTime, Attenuation, Concurrency, bAutoDestroy);

Spawn sound at location:

UAudioComponent* MySound = UGameplayStatics::SpawnSoundAtLocation(GetWorld(), SoundBase, Location, Rotation, VolumeMultiplier, PitchMultiplier, StartTime, Attenuation, Concurrency, bAutoDestroy);

Play sound:

UGameplayStatics::PlayDialogue2D(GetWorld(), DialogWave, DialogContext, VolumeMultiplier, PitchMultiplier, StartTime);
//
UGameplayStatics::PlayDialogueAtLocation(GetWorld(), DialogWave, DialogContext, Location, Rotation, VolumeMultiplier, PitchMultiplier, StartTime, Attenuation);
//
UGameplayStatics::PlayDialogue2D(GetWorld(), DialogWave, DialogContext, VolumeMultiplier, PitchMultiplier, StartTime);
//
UGameplayStatics::PlayDialogueAtLocation(GetWorld(), DialogWave, DialogContext, Location, Rotation, VolumeMultiplier, PitchMultiplier, StartTime, Attenuation);
//
UGameplayStatics::PlaySound2D(GetWorld(), SoundBase, VolumeMultiplier, PitchMultiplier, StartTime, Concurrency, Owner);
//
UGameplayStatics::PlaySoundAtLocation(GetWorld(), SoundBase, Location, Rotation, VolumeMultiplier, PitchMultiplier, StartTime, Attenuation, Concurrency, Owner);

Tracing and Overlap

If you are not using collision components and want to do a 1-off line trace or overlap, these are the functions for you!

GetWorld()->LineTraceMultiByChannel(HitsArray, Start, End, ECC_Visibility, TraceParams);
GetWorld()->LineTraceMultiByObjectType(HitsArray, Start, End, ObjectQueryParams, TraceParams);
GetWorld()->LineTraceMultiByProfile(HitsArray, Start, End, "ProfileName", TraceParams);
GetWorld()->LineTraceSingleByChannel(Hit, Start, End, ECC_Visibility, TraceParams);
GetWorld()->LineTraceSingleByObjectType(Hit, Start, End, ObjectQueryParams, TraceParams);
GetWorld()->LineTraceSingleByProfile(Hit, Start, End, "ProfileName", TraceParams);
GetWorld()->OverlapMultiByChannel(OverlapsArray, Location, FQuat::Identity, ECC_Visibility, FCollisionShape::MakeSphere(Radius), TraceParams);
GetWorld()->OverlapMultiByObjectType(OverlapsArray, Location, FQuat::Identity, ObjectQueryParams, FCollisionShape::MakeSphere(Radius), TraceParams);
GetWorld()->OverlapMultiByProfile(OverlapsArray, Location, FQuat::Identity, "ProfileName", FCollisionShape::MakeSphere(Radius), TraceParams);

Particles Systems

Particle Systems are used for a large variety of visual effects, such as smoke from an exhaust, dirt kicked up from running, splashing in water, sparks from loose wires.

Spawning particle emitters

UParticleSystemComponent* MyParticles = UGameplayStatics::SpawnEmitterAttached(ParticleSystem, AttachToComponent, AttachPointName, Location, Rotation, Scale, EAttachLocation::KeepRelativeOffset, bAutoDestroy);
//
UParticleSystemComponent* MyParticles = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ParticleSystem, Location, Rotation, Scale, bAutoDestroy);
//
UParticleSystemComponent* MyParticles = UGameplayStatics::SpawnEmitterAttached(ParticleSystem, AttachToComponent, AttachPointName, Location, Rotation, Scale, EAttachLocation::KeepRelativeOffset, bAutoDestroy);
//
UParticleSystemComponent* MyParticles = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ParticleSystem, Location, Rotation, Scale, bAutoDestroy);

Decals

Decals are materials that are projected onto a mesh in a level. Such as having graffiti on a wall, or adding dirty footsteps to a clean floor.

UDecalComponent* MyDecal = UGameplayStatics::SpawnDecalAttached(GetWorld(), DecalMaterialInterface, Size, AttachToComponent, AttachPointName, Location, Rotation, EAttachLocation::KeepRelativeOffset, lifeSpan);
//
UDecalComponent* MyDecal = UGameplayStatics::SpawnDecalAtLocation(GetWorld(), DecalMaterialInterface, Size, Location, Rotation, lifeSpan);

Timers

Timers will call a function at each DelayTime interval if looping.

// FTimerHandle TimerHandle;
// Starting a timer
GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &Class::Function, DelayTime, bLoop);
GetWorld()->GetTimerManager().SetTimer(TimerHandle, this, &Class::Function, DelayTime, bLoop, FirstDelay);
// Pausing/Resuming a timer
GetWorld()->GetTimerManager().PauseTimer(TimerHandle);
GetWorld()->GetTimerManager().UnPauseTimer(TimerHandle);
// Stopping/clearing a timer
GetWorld()->GetTimerManager().ClearTimer(TimerHandle);
TimerHandle.Invalidate();

Simple