AX2BaseActor::AX2BaseActor(TSubclassOf<UMeshComponent> MeshClass = UStaticMeshComponent::StaticClass())
{
// 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;
Mesh = CreateDefaultSubobject<MeshClass.Get()->GetClass()>(TEXT("Mesh"));
Mesh->SetMobility(EComponentMobility::Movable);
RootComponent = Mesh;
Item = CreateDefaultSubobject<UX2Item>(TEXT("Item"));
}
in the above code, i have a ClassType parameter called MeshClass, and i want to create its instance by calling
Mesh = CreateDefaultSubobject<MeshClass.Get()->GetClass()>(TEXT("Mesh"));
but this won’t work, error is pasted below:
note: 'UObject::CreateDefaultSubobject': invalid template argument for 'TReturnType', type expected
[7/14] Compile [x64] X2Axe.cpp
i do a lot search, but it seems that no clear answer. since MeshClass itself is a class type reference, it should be able to be passed as template parameter in generic functions.
thanks very much.
Not sure this is possible, or if I’d want to see it in any code, but I’d be interested to see the answer.
What is the type of “Mesh”? Also what is the use case?
You can use the non-templated CreateDefaultSubobject
version (which is called by the templated one) that takes additional const UClass* ReturnType, const UClass* ClassToCreateByDefault
parameters. ReturnType
would be UMeshComponent::StaticClass()
and ClassToCreateByDefault
would be *MeshClass
in your example.
If you’re using FObjectInitializer
you can call SetDefaultSubobjectClass
to set the override class to create instead. This is typically used directly in the subclass.
i want to create a base actor class, which can manage static and skeletal Mesh in one single property. this will help simply the code somehow. but after doing a lot lot search, i think this may not be possible, sad. thank u anyway.
thank u very much, this is what i needed for now. here is the final code
Mesh = Cast<UMeshComponent>(CreateDefaultSubobject(TEXT("Mesh"), UMeshComponent::StaticClass(), MeshClass, true, false));
sadly i’m not familiar with the forum, i think there is a button to mark as answer, i can not found it out.
but this is not a perfect solution, maybe i will encounter a similar scene, but without lucky to find another CreateDefaultSubobject to help. it do helps for the current problem.
1 Like