【问题标题】:How can I create an instance from a UObject class?如何从 UObject 类创建实例?
【发布时间】:2021-11-19 13:54:30
【问题描述】:

我有一个数据表,其中列出了敌人可以掉落的物品,以及它们的稀有度和最小/最大数量:

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)': 无法将参数 1 从 'TSubclassOf' 转换为 'UBattleItemBase *const &'

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

【问题讨论】:

    标签: c++ unreal-engine4


    【解决方案1】:

    DropItemClass 只是项目的类,而不是它的实例。

    如果您想从该类创建一个实例,您可以使用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,因此如果您希望它为任何对象所拥有,则应改为传递该参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-02
      • 2014-03-03
      • 2019-06-28
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多