Hi all, I’m a UE newbie so I’m still in the phase where 90% of my time working with Unreal is spent on online tutorial. That’s my problem: when I recompile the code, I had to replace every instance of my class already present in the scene with a new instance, or the game will crash while starting playing (furthermore on recompiling i can see the material applied to the mesh disappear in the editor). I have done some trials and as far as I have understood, this is caused by instantiating the Dynamic material in the constructor. Now I have two question: why this happens? And what’s should be initializated in the constructor and what in other method (like onConstruction(), beginPlay(), etc.)?
I have searched a lot, but I have found nothing to clarify this doubts. Below there is the code of my constructor.
// Sets default values
MyClass::MyClass()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don’t need it.
PrimaryActorTick.bCanEverTick = true;
// Collision component.
USphereComponent* SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere Component"));
SphereComponent->InitSphereRadius(40);
RootComponent = SphereComponent;
// Mesh component.
SphereVisual = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Visual Representation"));
SphereVisual->SetupAttachment(RootComponent);
static ConstructorHelpers::FObjectFinder<UStaticMesh> SphereVisualAsset(TEXT("StaticMesh'/Engine/BasicShapes/Sphere.Sphere'"));
if (SphereVisualAsset.Succeeded()) {
SphereVisual->SetStaticMesh(SphereVisualAsset.Object);
SphereVisual->SetWorldScale3D(FVector(0.8f));
}
// Instance Material.
static ConstructorHelpers::FObjectFinder<UMaterial> FoundMaterial(TEXT("/Game/Material/DummyMaterial.DummyMaterial"));
if (FoundMaterial.Succeeded()) {
UE_LOG(EditorLog, Log, TEXT("Material found."));
DynamicMaterial = UMaterialInstanceDynamic::Create(FoundMaterial.Object, SphereVisual);
SphereVisual->SetMaterial(0, DynamicMaterial);
}
}