- Unreal Engine 4.x Scripting with C++ Cookbook
- John P. Doran William Sherif Stephen Whittle
- 267字
- 2025-02-28 12:28:30
Specifying a UCLASS as the type of a UPROPERTY
So, you've constructed some custom UCLASS, intended for use inside UE4. We created one in the editor using blueprints in the previous recipe, but how do you instantiate them in C++? Objects in UE4 are reference-counted and memory-managed objects, so you should not allocate them directly using the C++ keyword new. Instead, you'll have to use a function called ConstructObject so that we can instantiate your UObject derivative.
ConstructObject doesn't just take the C++ class name of the object you are creating; it also requires a blueprint class derivative of the C++ class (a UClass* reference). A UClass* reference is just a pointer to a blueprint.
How do we instantiate an instance of a particular blueprint from the C++ code? C++ code does not, and should not, know concrete UCLASS names, since these names are created and edited in the UE4 editor, which you can only access after compilation. We need a way to somehow hand back the blueprint class name to instantiate with the C++ code.
The way we do this is by having the UE4 programmer select the UClass that the C++ code is to use from a simple drop-down menu listing all the blueprints available (derived from a particular C++ class) inside the UE4 editor. To do this, we simply have to provide a user-editable UPROPERTY with a TSubclassOf<C++ClassName> typed variable. Alternatively, you can use FStringClassReference to achieve the same objective.
UCLASS should be considered as resources to the C++ code, and their names should never be hardcoded into the code base.