How do I spawn a decal in C++?
There is a blueprint function called “SpawnDecalAtLocation” but there is no such function in C++.
I think you must use UDecalComponent
MyActor.cpp
#include "Components/DecalComponent.h"
AMyActor::AMyActor()
{
Decal = CreateDefaultSubobject<UDecalComponent>(L"Decal");
Decal->SetupAttachment(RootComponent);
}
MyActor.h
class MYPROJECT_API AMyActor : public AActor
{
GENERATED_BODY()
private:
class UDecalComponent * Decal;
};
UDecalComponent is a component, which you can’t (just?) spawn in the world.
Also, calling CreateDefaultSubobject will create a subobject for the class you are calling the function in, so in my case the player controller.
I figured it out:
ADecalActor* decal = GetWorld()->SpawnActor<ADecalActor>(hitResult.Location, FRotator());
if (decal)
{
decal->SetDecalMaterial(ActionDecalToSpawn);
decal->SetLifeSpan(2.0f);
decal->GetDecal()->DecalSize = FVector(32.0f, 64.0f, 64.0f);
m_previousActionDecal = decal;
}
else
{
UE_LOG(LogTemp, Warning, TEXT("No decal spawned"));
}
Note that ActionDecalToSpawn is a UMaterialInterface* (=Material).
You need to include
#include "Engine/DecalActor.h"
#include "Components/DecalComponent.h"
in the cpp file where you are spawning the decal actor.
I noticed when i tried to do this that the spawned location was being changed after the spawn. I’m unsure why this happens and its not just on decals but on other components. But to correct it all i do is set the transform on the spawned instance to fix it.
ADecalActor* SpawnedActor = GetWorld()->SpawnActor<ADecalActor>(ADecalActor::StaticClass(), FTransform(Rotation, Location, Scale), SpawnParams))
SpawnedActor->SetActorTransform(FTransform(Rotation, Location, Scale));
If anyone knows why this happens please let me know.
Something worth mentioning, the decal material can be assigned a UMaterialInstanceDynamic* and works perfectly well.