UE4 C++ 加载资源的几种方式

第一:静态加载资源
Actor类的.h文件夹中
public:
//加载类资源
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = UI)
TSubclassOf MyActor;

//加载模型资源
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = UI)
UStaticMeshComponent* MeshObj;

Actor类的.cpp文件夹中,静态加载方式一定是在构造函数中写
//静态加载模型资源
MeshObj = CreateDefaultSubobject(TEXT(“Mesh1”));
static ConstructorHelpers::FObjectFinder TmpMesh(TEXT(“StaticMesh’/Game/StarterContent/Shapes/Shape_NarrowCapsule.Shape_NarrowCapsule’”));
MeshObj->SetStaticMesh(TmpMesh.Object);
静态加载类
staticConstructorHelpers::FClassFinderMyActor2(TEXT(“BBlueprint’/Game/Blueprints/BP_LoadTest.BP_LoadTest_C’”));(注意加载类一定要加上_C)
MyActor = MyActor2.Class;

第二:SpawnActor动态生成一个Actor
ATemp spawnActor = GetWorld()->SpawnActor(ATemp::StaticClass());
或者写成:
ATemp* spawnActor = GetWorld()->SpawnActor((ATemp::StaticClass(), FVector::ZeroVector, FRotator::ZeroRotator);(注意:位置可以自己设置)*

第三:LoadObject和LoadClass
一、LoadObject
UStaticMesh* TempMesh = LoadObject(NULL,TEXT(“StaticMesh’/Game/StarterContent/Props/SM_Chair.SM_Chair’”));
if(TempMesh != nullptr)
{
MeshComponent->SetStaticMesh(TempMesh);
}
二、LoadClass
第一种方式:
UObject* loadTestObj = StaticLoadObject(UBlueprint::StaticClass(), NULL, TEXT(“Blueprint’/Game/BluePrint/BP_Test.BP_Test’”));
if (loadTestObj != nullptr)

UBlueprint* ubpTest = Cast(loadTestObj);
AActor* spawnActor = GetWorld()->SpawnActor(ubpTest->GeneratedClass);
UE_LOG(LogTemp, Warning, TEXT(“Success”));

第二种方式:
UClass* Class = nullptr;
Class = Cast(StaticLoadObject(UClass::StaticClass(), nullptr, TEXT(“Blueprint’/Game/BluePrint/BP_Test.BP_Test_C’”)));****(注意_C)
AActor* spawnActor = GetWorld()->SpawnActor(Class);

以上都可使用

猜你喜欢

转载自blog.csdn.net/qq_43021038/article/details/124836006