Common Snippets In C++

From UE4: Community Wiki
Jump to: navigation, search
This article is a preliminary version, it is subject to change.

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[edit]

UCLASS[edit]

Declaration of the most basic UCLASS

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


USTRUCT[edit]

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[edit]

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[edit]

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) {}


Interfacing with blueprints:

Making something callable from blueprint: Header .h file :

UFUNCTION(BlueprintCallable)
AActor* MyFunctionName(int argSomeParameter, FMyStruct& OutStruct); 
// Can have any return type or parameters you want, so long as the types are recognized by blueprints.
// The function can be const, but none of the parameters can be const.

Body .cpp file:

UFUNCTION(BlueprintCallable)
AActor* UMyUniqueClass::MyFunctionName(int argSomeParameter, FMyStruct& OutStruct)
{
    // Define as normal.
}

Blueprint Native Event. This means the function has a default behavior in C++ that a blueprint class can override. You can also make the default virtual and inherit it in C++ too. UMyBaseUnrealClass.h file:

public:
UFUNCTION(BlueprintNativeEvent)
AActor* MyNativeFunction(int argSomeParameter, FMyStruct& OutStruct); // The UFUNCTION cannot be marked virtual.

protected:
virtual AActor* MyNativeFunction_Implementation(int argSomeParameter, FMyStruct& OutStruct); // This function MUST be named identical to the UFUNCTION plus "_Implementaton".
// This can be marked as virtual and overriden.
// Being protected is optional but highly recommended.  The implementation should never be called directly except when making an override.

UMyBaseUnrealClass.cpp file:

// Only define the _Implementation function, not the original.
Actor* UMyBaseUnrealClass::MyNativeFunction_Implementation(int argSomeParameter, FMyStruct& OutStruct)
{
   // default behavior here.
}

Inheriting in C++. UMyDerivedUnrealClass.h

UMyDerivedUnrealClass : public UMyBaseUnrealClass
{
// ...
protected:
AActor* MyNativeFunction_Implementation(int argSomeParameter, FMyStruct& OutStruct) override;  // Override the implementation.
};

UMyDerivedUnrealClass.cpp

Actor* UMyBaseUnrealClass::MyNativeFunction_Implementation(int argSomeParameter, FMyStruct& OutStruct)
{
   // To call the previous behavior.
   Super::MyNativeFunction_Implementation(argSomeParameter, OutStruct); // Do not call the UFUNCTION on the parent class or you will get an infinite loop.
   // Extra behavior here.
   // You can inherit as many times as you want with additional classes.
}


UINTERFACE[edit]

Basic example of header of UINTERFACE

For more info, see Interfaces_In_C++

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

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

Components[edit]

Creating a spring arm and camera[edit]

Creating a camera component from inside an actor constructor

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

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

Overlapping Collision Components[edit]

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[edit]

Logging[edit]

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);

Declare and Define Log Category[edit]

/** MyClass.h */
// Preprocessor statements
DECLARE_LOG_CATEGORY_EXTERN(MyLogCategoryTitle, Warning, All);
/** MyClass.cpp */
// Preprocessor statements
DEFINE_LOG_CATEGORY(MyLogCategoryTitle);

void MyClass::Foo()
{
  UE_LOG(MyLogCategoryTitle, Warning, TEXT(""));
}

Define Log Category Static[edit]

/** MyClass.cpp */
// Preprocessor statements
DEFINE_LOG_CATEGORY_STATIC(MyLogCategoryTitle, Warning, All);

void MyClass::Foo()
{
   UE_LOG(MyLogCategoryTitle, Warning, TEXT(""));
}

Getting Things[edit]

Get all actors


GetAllActors* is an expensive operation


// TArray<AActor*> 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. This will return it as the base UActorComponent class.

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

Get a component with casting from inside an Actor

USomeActorComponent* myComponent = Cast<USomeActorComponent>(GetComponentByClass(USomeActorComponent::StaticClass()));
// Templatized version
USomeActorComponent* myComponent = FindComponentByClass<USomeActorComponent>();

Get all components from inside an Actor

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

Actor iterator

#include "EngineUtils.h"

for (TActorIterator<AActor> It(GetWorld()); It; ++It)
{
    AActor* MyActor = *It;
    break;
}

Input[edit]

Basic Input and Action binding.

The following string "Button" and "MoveForward" additionally need to be defined in Edit->Project Settings->Input->Bindings->Add to Action Mappings or Axis Mappings.

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

You can bind other classes to respond to a pawn's input as well

void UMyActorComponent::BeginPlay()
{
APawn* OwnerPawn = Cast<APawn>(GetOwner());
OwnerPawn->InputComponent->BindAction("Button", EInputEvent::IE_Pressed, this, &MyActorComponent::ButtonPressed);
}
...
void UMyActorComponent::ButtonPressed() {}

Saving[edit]

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

UCLASS()
class SOMEGAME_API UMySaveGame : public USaveGame
{
    GENERATED_BODY()
public:
    UPROPERTY(VisibleAnywhere)    
    float HighScore();
};

Then you can save and load as follows:

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

Load from the save and set appropriate value.

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

Spawning Actors[edit]

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<AMyClass>(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<AClass>(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);

// Can also call FinishSpawning on the actor which has extra (optional) parameters if needed
ActorName->FinishSpawning(ActorTransform, bIsDefaultTransform, ComponentInstanceDataCache);

Audio[edit]

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[edit]

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[edit]

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[edit]

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[edit]

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[edit]