Hello,
I have a question regarding converting a blueprint class to its parent C++ class that I hope someone can help clarify.
I have a C++ class called A which inherits from UObject. I then created a blueprint class called BP_A that inherits from A. When I load BP_A in C++ code, I get back a UBlueprintGeneratedClass object.
My question is, how can I convert this UBlueprintGeneratedClass to an object of class A?
From my research, I’m guessing that the blueprint may just act like a template, and that I need to use the UBlueprintGeneratedClass to call NewObject to instantiate an object from it.
I would greatly appreciate if anyone could confirm my understanding or provide guidance on the proper way to convert a loaded blueprint class to its parent C++ class.
Thank you very much for your time and assistance!
Hi! If I’m reading your question properly, I think you might be looking for TSubclassOf
. If you create a UPROPERTY
like this
UPROPERTY(EditDefaultsOnly)
TSubclassOf<A> A;
then you will be able to assign blueprint subclasses to this variable in the editor, while your c++ code sees an instance of A
. It is also type-safe in the sense that the editor won’t allow you to assign BPs of the wrong type to this property.
You can read more about TSubclassOf
here:
Typed Object Pointer Properties in Unreal Engine | Unreal Engine 5.2 Documentation
I apologize for not providing enough clarity in my previous question. To clarify, what I need is to obtain a UObject instance of class A, not its UClass.
For example, I have loaded a blueprint resource in this way:
UClass* TestObj = LoadClass<A>(nullptr, TEXT("Blueprint'/Game/BP_A.BP_A_C'"));
However, I’m only getting the blueprint’s UClass. What I actually want is to get a UObject instance of class A from this blueprint.
I know that if class A inherits from AActor, I would need to use SpawnActor to get the actual Actor instance. But I haven’t seen whether inheriting from UObject requires using NewObject to obtain the UObject instance.
So I wanted to confirm whether I need to use TSubclassOf to call NewObject in order to achieve this.
For instance, class A has a member attribute m_A that I want to access. So is there any way to get the value of this member attribute directly from the TSubclassOf< A >, or do I have to use NewObject?
Thanks
Yes, you would use NewObject to create an instance of your class. NewObject has an overloads that allows you to pass in additional type information so that you can do:
CPP_Type *Instance = NewObject< CPP_Type >( Outer, ClassRef )
Thank you for the insightful explanation. It perfectly answered my questions and cleared up my confusion. I really appreciate you taking the time to help me understand this properly.
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.