CreateDefaultSubobject with SubClassOf

I have a UMyActorComp : UActorComponent that I am finding I need to do stuff with as a Blueprint, I should only need 1 Blueprint Type, and “shouldn’t” need to derive further.

currently I have

UPROPERTY(EditAnywhere, BlueprintReadOnly)
TObjectPtr<UMyActorComp> ActorComp;

AMyActor() 
{
    ActorComp = CreateDefaultSubobject<UMyActorComp>(TEXT("ActorComp"));
}

then I start doing work with it during PostInitializeComponents() (passing pointers, and registering it to relevant subsystem managers)

so because I now need a blueprint version

UPROPERTY(EditDefaultsOnly)
TSubclassOf<UMyActorComp> ActorCompBlueprint;
UPROPERTY(EditAnywhere, BlueprintReadOnly)
TObjectPtr<UMyActorComp> ActorComp;

AMyActor()
{
    if( ActorCompBlueprint == nullptr )
    {
		UE_LOG(LogTemp, Error, TEXT("Set ActorCompBlueprint for %s"), *GetName());
		ActorCompBlueprint = UMyActorComp::StaticClass();
	}
	ActorComp = CreateDefaultSubobject<UMyActorComp>(FName(TEXT("ActorComp")), UMyActorComp::StaticClass(), ActorCompBlueprint.Get(), true, false);
        }
}

this throws an error at code analysis:

"no instance of overloaded function “AMyActor::CreateDefaultSubobject” matches the argument list argument types are: (FName, UClass*, UClass*, bool, bool)
when this is overload 1.

new Object in the constructor ActorComp = NewObject<UMyActorComp>(this, ActorCompBlueprint.Get(), TEXT("ActorComp)); crashes

supposedly the suggestions I have found is use NewObject during PostIntializeComponents() which I need the object to exist by that point (assigning pointers to, and trusting it to be a valid pointers so they can be registered to relevent subsystem managers and there is no hitch right at BeginPlay)

If you want to use a blueprint component then you’ll have to add it in blueprint, and then I suppose you can do GetComponentByClass in PostInitializeComponents if you want to access it through C++

this works, I hate it, but it works, needed an error message and forced return in PostInitializeComponents() to prevent a crash.

used FindComponentByClass<T>() where it has the cast built in.

void AMyActor::PostInitializeComponents()
{
    Super::PostInitializeComponents();
    if( ActorComp == nullptr )
    {
        if( !(ActorComp = FindComponentByClass<UMyActorComp>()) )
        {
			UE_LOG(LogTemp, Error, TEXT("ActorComp unassigned for blueprint of %s"), *GetName());
			return;
        }
    }
}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.