Creating class instances in C++ is traditionally done using the keyword new
. However, UE4 actually creates instances of its classes internally, and requires you to call special factory functions to produce copies of any UCLASS
that you want to instantiate. You produce instances of the UE4 Blueprints classes, not the C++ class alone. When you create UObject
-derived classes, you will need to instantiate them using special UE4 Engine functions.
The factory method allows UE4 to exercise some memory management on the object, controlling what happens to the object when it is deleted. This method allows UE4 to track all references to an object so that on object destruction, all references to the object can be easily unlinked. This ensures that no dangling pointers with references to invalidated memory exist in the program.
Instantiating UObject
-derived classes that are not AActor
class derivatives does not use UWorld::SpawnActor< >
. Instead, we have to use special global functions named ConstructObject< >
, or NewObject< >
. Note that you should not use the bare C++ keyword new
to allocate new instances of your UE4 UObject
class derivatives.
You will need at least two pieces of information to properly instantiate your UCLASS
instance:
UClass
reference to the class type that you would like to instantiate (Blueprint class)GameMode
object), add a TSubclassOf< YourC++ClassName > UPROPERTY()
to specify and supply the UCLASS
name to your C++ code. For example, we add the following two lines to our GameMode
object:UPROPERTY( EditAnywhere, BlueprintReadWrite, Category = UClassNames ) TSubclassOf<UUserProfile> UPBlueprintClassName;
UClass
name from the drop-down menu so that you can see what it does. Save, and exit the editor.UCLASS
instance.ConstructObject< >
with the following formula:ObjectType* object = ConstructObject< ObjectType >( UClassReference );
For example, using the UserProfile
object that we specified in the last recipe, we would get code like this:
// Get the GameMode object, which has a reference to // the UClass name that we should instantiate: AChapter2GameMode *gm = Cast<AChapter2GameMode>( GetWorld()->GetAuthGameMode() ); if( gm ) { UUserProfile* object = ConstructObject<UUserProfile>( gm->UPBlueprintClassName ); }
Instantiating a UObject
class using ConstructObject
or NewObject
is simple. NewObject
and ConstructObject
do nearly the same thing: instantiate an object of Blueprint class type, and return a C++ pointer of the correct type.
Unfortunately, NewObject
has a nasty first parameter which requires you to pass GetTransientPackage()
with each call. ConstructObject
does not require this parameter with each call. In addition, ConstructObject
provides you with more construction options.
Do not use the keyword new
when constructing your UE4 UObject
derivative! It will not be properly memory-managed.
3.142.199.191