第一种: 如果该蓝图有C++类(或者说是从C++类创建的蓝图)
ATemp* spawnActor = GetWorld()->SpawnActor(ATemp::StaticClass());
所有的加载资源并创建到场景中的方式都离不开SpawnActor这一句代码.如果你的蓝图包含了C++类,那么可以直接访问类的StaticClass
第二种: 通过ConstructorHelpers来加载(只能在类的构造函数中使用)
static ConstructorHelpers::FClassFinder bpClass(TEXT("/Game/BluePrint/TestObj"));
if(bpClass.Class != NULL)
{
GetWorld()->SpawnActor(bpClass.Class);
}
FClassFinder是一个结构体,其中的Class成员变量是TSubClassof类型的.所以我们只需要SpawnActor(bpClass.Class)就可以生成我们要的东西了 该方法在一开头的地方就先检查了是否在构造函数中CheckIfIsInConstructor,另外一点,该变量必须是static的
struct FClassFinder
{
TSubclassOf Class;
FClassFinder(const TCHAR* ClassToFind)
{
CheckIfIsInConstructor(ClassToFind);
FString PathName(ClassToFind);
StripObjectClass(PathName, true);
Class = ConstructorHelpersInternal::FindOrLoadClass(PathName, T::StaticClass());
ValidateObject(*Class, PathName, *PathName);
}
bool Succeeded()
{
return !!*Class;
}
};
第三种: 通过FStringAssetReference来加载
FStringAssetReference asset = "Blueprint'/Game/BluePrint/TestObj.TestObj'";
UObject* itemObj = asset.ResolveObject();
UBlueprint* gen = Cast<UBlueprint>(itemObj);
if (gen != NULL)
{
AActor* spawnActor = GetWorld()->SpawnActor<AActor>(gen->GeneratedClass);
}
FStringAssetReference类的作用主要是通过一个字符串,找到该字符串所对应的资源.或者通过给定的资源,找到该资源所对应的在项目中的路径,也就是前面所说的字符串 其中,asset.ResolveObject就是查找字符串对应的资源,返回一个UObejct,我们通过将其转化成UBlueprint类型然后再取的他的GenerateClass即可
第四种: 通过StaticLoadObject来加载
UObject* loadObj = StaticLoadObject(UBlueprint::StaticClass(), NULL, TEXT("Blueprint'/Game/BluePrint/TestObj.TestObj'"));
if (loadObj != nullptr)
{
UBlueprint* ubp = Cast(loadObj);
AActor* spawnActor = GetWorld()->SpawnActor(ubp->GeneratedClass);
UE_LOG(LogClass, Log, TEXT("Success"));
}
✔动态加载资源:Material跟Texture(材质和贴图)
示例1:
动态加载的工具方法
UTexture2D* MyTextureLoader::LoadTextureFromPath(const FString& Path) { if (Path.IsEmpty()) return NULL; return Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(), NULL, *(Path))); }
调用:
FString PathToLoad = "/Game/Textures/YourStructureHere"; UTexture2D* tmpTexture = LoadTextureFromPath(PathToLoad);
示例2:
加载Material和Texture
struct FConstructorStatics { ConstructorHelpers::FObjectFinderOptional<UTexture> TextureFinder; ConstructorHelpers::FObjectFinderOptional<UMaterial> MaterialFinder; FConstructorStatics() : TextureFinder(TEXT("Texture2D'/Game/Textures/2DBackground.2DBackground'")) , MaterialFinder(TEXT("Material'/Game/Materials/DynamicTextureMaterial.DynamicTextureMaterial'")) { } }; static FConstructorStatics ConstructorStatics; Texture = ConstructorStatics.TextureFinder.Get(); UMaterial* Material = ConstructorStatics.MaterialFinder.Get(); DynamicMaterial = UMaterialInstanceDynamic::Create(Material, this);
设置调用加载好的Material和Texture:
DynamicMaterial->SetTextureParameterValue(FName("DynamicTexture"), Texture); Mesh->SetMaterial(0, DynamicMaterial);
如果资源永不再使用,想销毁资源对象,代码如下:
Texture2D* mytex; //这里假设mytex合法有效 mytex->ConditionalBeginDestroy(); mytex = NULL; GetWorld()->ForceGarbageCollection(true);