如何从 UObject class 创建实例?

How can I create an instance from a UObject class?

我有一个数据表,其中包含敌人可以掉落的物品列表,以及它们的稀有性和 min/max 数量:

USTRUCT(BlueprintType)
struct FItemDropRow : public FTableRowBase
{
    GENERATED_BODY()

    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    TSubclassOf<UBattleItemBase> DropItemClass;

    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    EItemRarity RarityTier;

    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    int MinDrop;

    UPROPERTY(EditAnywhere, BlueprintReadOnly)
    int MaxDrop;
};

下面是选择掉落的角色的函数:

// Pick a random entry from a list of items filtered by rarity
int SelectedIndex = FMath::RandRange(0, UsableRowIndexArray.Num() - 1);

// Retrieve that entry from the DataTable
FItemDropRow* SelectedRow = ItemDropDataTable->FindRow<FItemDropRow>(
    UsableRowIndexArray[SelectedIndex],
    ContextString
);

// Pick a random amount to drop from the min/max defined on the DataTable row
int DropQuantity = FMath::RandRange(
    SelectedRow->MinDrop,
    SelectedRow->MaxDrop
);

// Initialize the array with the item instance and the quantity to add
TArray<UBattleItemBase*> ItemsToReturn;
ItemsToReturn.Init(SelectedRow->DropItemClass, DropQuantity);
return ItemsToReturn;

问题是 DataTable 仅存储对 类:

的引用
C2664   'void TArray::Init(UBattleItemBase *const &,int)':
    cannot convert argument 1 from 'TSubclassOf' to 'UBattleItemBase *const &'

但我需要它作为一个实例,这样我就可以将它添加到玩家的库存中并修改它的数量。我已经在 FItemDropRow 结构中尝试了 Instanced 标志,但这会导致 DropItemClass 在 DataTable

中不再显示为可编辑的 属性

DropItemClass 只是项目的 class,不是项目的实例。

如果您想从 class 创建一个实例,您可以使用 NewObject() 或更高级的版本之一(NewNamedObject() / ConstructObject()CreateObject(), 等等...)

例如:

TArray<UBattleItemBase*> ItemsToReturn;
for(int i = 0; i < DropQuantity; i++)
    ItemsToReturn.Add(NewObject<UBattleItemBase>(
        (UObject*)GetTransientPackage(),
        SelectedRow->DropItemClass
    ));

这将创建指定 DropItemClassDropQuantity 个实例。

NewObject() 的第一个参数将是新创建对象的 outer,因此如果您希望它被任何对象拥有,您应该传递那个对象。