Почему сохраняется состояние поля класса?

Имеется следующий метод

bool UISStorageComponent::AddNewItem(AISBaseItem* Item)
{
	if (Item == nullptr)
	{
		UE_LOG(ISStorageComponentLog, Error, TEXT("The item is nullptr!!!"));
		return false;
	}

	FCurrentItems NewItem;
	NewItem.Item = Item->GetClass();
	CurrentStorageItems.Add(NewItem);

	AISBaseItem* AddedItem = Cast<AISBaseItem>(NewItem.Item->GetDefaultObject());

	UE_LOG(ISStorageComponentLog, Error, TEXT("Item QT %d"), AddedItem->Quantity);


	int32 TotalItems, TotalInAllStacs;
	if (UseWeight){
		float NewWeight;
		RecountWeight(NewWeight);
	}
	RecountItems(TotalItems, TotalInAllStacs);
	AddedItem->SetOwningStorage(this);
	Item->DestroyItem();
	return true;
}


Проблема в том что при выполнении
CurrentStorageItems.Add(NewItem);
Поле Quantity в NewItem имеет значение из прошлого запуска -1
Видео для наглядности.

В общем и целом делается инвентарь, в котором хранятся классы объектов. Сами объекты "подобранные с сцены" удаляются. и в поле CurrentStorageItems хранится массив структур FCurrentItems с самими классами предметов.

USTRUCT(BlueprintType)
struct FCurrentItems
{
	GENERATED_BODY()

	UPROPERTY(EditAnywhere, BlueprintReadWrite)
	TSubclassOf<AISBaseItem> Item;

};

	//Current items in storage
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
		TArray<FCurrentItems> CurrentStorageItems;


UE 5.1.1 VS 2022
  • Вопрос задан
  • 67 просмотров
Решения вопроса 1
@trjflash Автор вопроса
В общем, вполне логично что состояние сохраняется так как меняется именно оно. Переписал хранение полей предмета в структуру и в инвентарь теперь добавляется эта самая структура
USTRUCT(BlueprintType)
struct FItemInfo {
	GENERATED_USTRUCT_BODY()

	//Item class
	UPROPERTY(EditAnywhere, BlueprintReadWrite)
	TSubclassOf <class AISBaseItem > ItemClass;
	//Item name
	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		FString ItemName;
	//Item icon
	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		UTexture2D* ItemIcon;
	//Item type
	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		EItemType ItemType;
	//Item weight
	UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (EditConditionHides, ClampMin = "0.0"))
		float ItemWeight;
	//Item durability
	UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (EditConditionHides, ClampMin = "0"))
		int32 CurrentDurability;
	//Item max durability
	UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (EditConditionHides, ClampMin = "0"))
		int32 MaxDurability;
	//Item quantity
	UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (EditCondition = "bIsStackable", EditConditionHides, ClampMin = "0", ClampMax = "9999"))
		int32 CurrentStackCount;
	// Max in stack
	UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (EditCondition = "bIsStackable", EditConditionHides, ClampMin = "0", ClampMax = "9999"))
		int32 MaxStackCount;
	// Max in stack
	UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (EditCondition = "bIsStackable"))
		bool bIsFullStack;
	//is item stackable
	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		bool bIsStackable;

	//is item equipable
	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		bool bIsEquipable;
	//is item usable
	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		bool bIsUsable;
	//is quest item
	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		bool bIsQuestItem;

	//Storage
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
		class UISStorageComponent* StorageOwner;

	bool operator==(const FItemInfo& Other) const
	{
		return ItemName == Other.ItemName &&
			ItemIcon == Other.ItemIcon &&
			ItemType == Other.ItemType &&
			ItemWeight == Other.ItemWeight &&
			CurrentDurability == Other.CurrentDurability &&
			MaxDurability == Other.MaxDurability &&
			MaxStackCount == Other.MaxStackCount &&
			bIsFullStack == Other.bIsFullStack &&
			bIsStackable == Other.bIsStackable &&
			bIsEquipable == Other.bIsEquipable &&
			bIsUsable == Other.bIsUsable &&
			bIsQuestItem == Other.bIsQuestItem;
	}
	bool operator!=(const FItemInfo& Other) const
	{
		return !(*this == Other);
	};
};


bool UISStorageComponent::AddItem(AISBaseItem* ItemToAdd, bool ForceAddNew) {

	if (!CanItemBeAdded(ItemToAdd)) return false;
	int32 TotalItems, TotalInAllStacs, ItemIndex, AddedItemIndex;
	float TotalWeight;
	
	if (!SearchItemInInventory(ItemToAdd->ItemInfo, ItemIndex)) {
		AddedItemIndex = CurrentItems.Add(ItemToAdd->ItemInfo);
		RecountItems(TotalItems, TotalInAllStacs);
		if (bUseWeightSystem)
			RecountWeight(TotalWeight);
		ItemToAdd->Destroy();
		CurrentItems[AddedItemIndex].StorageOwner = this;
		return true;
	}
	else if (!ForceAddNew) {
		AddItemToStack(ItemToAdd);
	}
	else {
		AddedItemIndex = CurrentItems.Add(ItemToAdd->ItemInfo);
		RecountItems(TotalItems, TotalInAllStacs);
		if (bUseWeightSystem)
			RecountWeight(TotalWeight);
		ItemToAdd->Destroy();
		CurrentItems[AddedItemIndex].StorageOwner = this;
		return true;
	}

	return false;
}


bool UISStorageComponent::AddItemToStack(AISBaseItem* Item)
{
	if (!CheckItem(Item)) return false;
	float TotalWeight;
	int32 TotalItems, TotalInAllStacs;

	if (!Item->ItemInfo.bIsStackable) {
		UE_LOG(ISStorageComponentLog, Display, TEXT("The item is unstackable"));
		return false;
	}

	for (int32 i = 0; i < CurrentItems.Num(); i++) {
		if (CurrentItems[i].ItemClass == Item->ItemInfo.ItemClass && CurrentItems[i].bIsFullStack != true) {
			int32 AvailableStackCount = CurrentItems[i].MaxStackCount - CurrentItems[i].CurrentStackCount;

			if (Item->ItemInfo.CurrentStackCount <= AvailableStackCount) {
				CurrentItems[i].CurrentStackCount += Item->ItemInfo.CurrentStackCount;
				if (bUseWeightSystem)
					RecountWeight(TotalWeight);

				RecountItems(TotalItems, TotalInAllStacs);

				if (CurrentItems[i].CurrentStackCount == CurrentItems[i].MaxStackCount)
					CurrentItems[i].bIsFullStack = true;
				Item->Destroy();
				return true;
			}
			else {
				int32 ToCurrentStack = CurrentItems[i].MaxStackCount - CurrentItems[i].CurrentStackCount;
				int32 ExtraQuantity = Item->ItemInfo.CurrentStackCount - ToCurrentStack;

				CurrentItems[i].CurrentStackCount = CurrentItems[i].MaxStackCount;
				if (bUseWeightSystem)
					RecountWeight(TotalWeight);

				RecountItems(TotalItems, TotalInAllStacs);
				CurrentItems[i].bIsFullStack = true;

				Item->ItemInfo.CurrentStackCount = ExtraQuantity;
				AddItem(Item, true);
				return true;
			}
		}
	}

	return false;
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы