首页 > 解决方案 > UE4:随机生成继承自单个 C++ 类的蓝图类actor

问题描述

我正在虚幻引擎中制作一个系统来生成我的角色可以拾取的物品。我在头文件中有一个 Item C++ 类:

UPROPERTY(EditAnywhere)
bool Inventoriable;

UPROPERTY(EditAnywhere)
float Power;

UPROPERTY(EditAnywhere)
int Spawn_Weight;

在我的游戏模式标题中,我有一个数组用于保存所有可能的项目

UPROPERTY(EditAnywhere)
TArray<TSubclassOf<AItem>> PlayerRecharge;

在 cpp 文件中,我有一个 SpawnPlayerRecharge() 函数,如下所示:

for (int i = 0; i < NUM_ITEMS; i++) {
    Item_Spawned = Cast<AItem>(PlayerRecharge[i]);
    if (Item_Spawned) {
        Total_Spawn_Weights += Item_Spawned->Spawn_Weight;
    }
}

// Choose random number for spawn selection
int Rand = FMath::RandRange(0, Total_Spawn_Weights);

// Iterates through spawnable items and tries to cast as Item object
// Weight variable stores the summed weights to compare to the random number
//if Weight > the random number, store the index in Weight and break from loop
int Weight = 0;
for (int i = 0; i < NUM_ITEMS; i++) {
    Item_Spawned = Cast<AItem>(PlayerRecharge[Weight]);
    if (Item_Spawned) {
        Weight += Item_Spawned->Spawn_Weight;
        if (Weight > Rand) {
            Weight = i;
            break;
        }
    }
}

FActorSpawnParameters Params;
Params.Owner = this;

// Spawn AItem actor from the array based on index found above
GetWorld()->SpawnActor<AItem>(PlayerRecharge[Weight], SpawnPosition, SpawnRotation, Params);

基本上,我拥有的所有类型的项目都在从具有不同网格、Power 属性等的 Item 继承的 Blueprint 类中。在 SpawnPlayerRecharge() 中,我试图根据每个孩子的权重随机生成一种不同的类型蓝图编辑器。在函数中,转换总是失败(我检查了 UE_LOG),如果我尝试使用 PlayerRecharge[i] 直接访问权重,它会给我一个错误,说 UOBJECT 没有属性 Spawn_Weight。我如何访问这些蓝图子项,或者有更好的方法吗?

如果你需要查看我没有发布的代码,它在我的 GitHub 上:https ://github.com/Chriq/BatteryMan

标签: c++unreal-engine4unreal-blueprint

解决方案


推荐阅读