[UE4] Several poses for creating objects (C++)


DEMO source code

No, you need to practice by yourself


Create components

In UE4, to create components for Actor, you can use the UObject::CreateDefaultSubobject() template function, as shown below:

/* <CreateObjectDemo> * 创建Component对象,要使用CreateDefaultSubobject模板函数 */
MyComponent = CreateDefaultSubobject<UMyActorComponent>(TEXT("MyComponent"));

load resource object

In UE4, all resource files in the project should not be regarded as files, but should be understood as "static objects": that is, the product of object serialization. To load project resources, you can use the "UObject::StaticLoadObject()" function, where the important parameter is the Name of the object, not the file path. The bottom layer of UE provides the file reading function, no matter whether the resource file is stored in my independent .uasset file or stored in a .PAK file, there is no need to care about the upper layer.

/* <CreateObjectDemo> * 加载模型、贴图等对象,使用StaticLoadObject函数 */ 
UStaticMesh* SM_Vase = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/Game/Assets/StaticMeshes/SM_Vase")) ); 
StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent")); 
StaticMeshComponent->SetStaticMesh(SM_Vase);

Create an Actor object

To create an Actor object, you need to use the UWorld::SpawnActor() interface, as shown below:

/* <CreateObjectDemo> * 创建AActor派生类对象不要用NewObject或new,而要用UWorld::SpawnActor() */ 
UWorld* World = GetWorld(); FVector pos(150, 0, 20); 
AMyActor* MyActor = World->SpawnActor<AMyActor>(pos, FRotator::ZeroRotator);

Create a UObject object

If you have a derived class of UObject (non-Actor, non-ActorComponent), then you can use the NewObject() template function to create its instance object.

/* <CreateObjectDemo> * 使用NewObject模板函数,来创建UObject派生类对象 */ 
MyObject = NewObject<UMyObject>();

Precautions

1.CreateDefaultSubobject must be written in the no-argument constructor of Actor , otherwise it will crash;
2.The TEXT or FName parameter in CreateDefaultSubobject cannot be repeated in the same Actor , otherwise it will crash;
3.UE4 does not recommend try catch, and it does not support it by default Yes, UE4 recommends Assertions.
https://answers.unrealengine.com/questions/264921/cannot-use-try-with-exceptions-disabled.html
https://docs.unrealengine.com/latest/INT/Programming/Assertions/index.html


Article reproduced from

Guess you like

Origin blog.csdn.net/ZFSR05255134/article/details/123051090