I have a problem with the Constructor Helpers. I MUST create the UTexture and UMaterialInterface inside the constructor. But the UTexture must be set through a variable. So how can I set this variable prior to construction? I tried BeginDeferredActorSpawnFromClass() but that didn’t help at all. SpawnActorDeferred() also did not work. It seems that those only work for Blueprint constructors but not for the C++ ones.
Please tell me there is a way to do this without me having to initialize ALL possible textures in the actor. I also tried a static TArray as a workaround but the moment I used it I get a LNK1120.
Spawning it:
JobMarker = Cast<AJobMarker>(UGameplayStatics::BeginDeferredActorSpawnFromClass(this, AJobMarker::StaticClass(), GetTransform()));
if (JobMarker != nullptr)
{
JobMarker->Init(MarkerTexturePath);
UGameplayStatics::FinishSpawningActor(JobMarker, GetTransform());
}
else
{
LOG_ERROR("Failed to spawn JobMarker.")
}
The actor that I’m trying to spawn:
AJobMarker::AJobMarker()
{
PrimaryActorTick.bCanEverTick = true;
<snip>
Material = ULib::CreateObject<UMaterialInterface>("/Game/Materials/MI_MarkResource");
Texture = ULib::CreateObject<UTexture>(TexturePath); // <<< This line is the problem
}
void AJobMarker::Init(FString texturePath) // This Init is too late!
{
TexturePath = texturePath;
}
// Called when the game starts or when spawned
void AJobMarker::BeginPlay()
{
Super::BeginPlay();
SetMarkerMaterial();
}
void AJobMarker::SetMarkerMaterial()
{
FMaterialSpriteElement element;
element.bSizeIsInScreenSpace = false;
element.BaseSizeX = 128.0f;
element.BaseSizeY = 128.0f;
MBB_Comp->Elements.Add(element);
if (Material != nullptr)
{
UMaterialInstanceDynamic* newMaterialInstance = MBB_Comp->CreateDynamicMaterialInstance(0, Material);
if (newMaterialInstance != nullptr)
{
newMaterialInstance->SetTextureParameterValue(FName("Texture"), Texture); // This line requires the GEngine so do NOT call this from a constructor.
MBB_Comp->SetMaterial(0, newMaterialInstance);
}
else
{
LOG_ERROR("MaterialInstance is NULL.")
}
}
else
{
LOG_ERROR("Material is NULL.")
}
}