RIght now I feel like I’ve been spending more time on here…
I am currently creating a basic inventory system.
This is my Master class Item.h
};
UCLASS()
class AItem : public AActor
{
GENERATED_BODY()
/** METODS **/
public:
AItem();
UWidgetComponent* GetWidgetComponent();
void SetVisibilityComponentON();
void SetVisibilityComponentOFF();
virtual void Interact() {}
virtual void BeginPlay() override;
UBoxComponent* GetCollision();
protected:
void ResetCollisionResponse();
private:
/** PROPERTIES **/
public:
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite)
UWidgetComponent* InteractPrompt = nullptr;
FItemData ItemInfo;
UPROPERTY(EditDefaultsOnly)
int32 MAX_STORAGE;
protected:
UPROPERTY(VisibleAnywhere)
UBoxComponent* BoxCollision = nullptr;;
private:
};
The struct gets stored in a TArray ItemDataList;
Which has a child class Medikit.
Upon interacting with the medikit, there is this function:
void AMedikit::Interact()
{
Super::Interact();
UFPSGameInstance* GameInstance = Cast<UFPSGameInstance>(GetGameInstance());
if (GameInstance != nullptr)
{
FItemData* ExistingItemData = nullptr;
for (FItemData& Data : GameInstance->ItemDataList)
{
if (Data.ItemName == ItemInfo.ItemName)
{
ExistingItemData = &Data;
break;
}
}
if (ExistingItemData != nullptr)
{
if (ExistingItemData->StoredQuantity < MAX_STORAGE)
{
ExistingItemData->StoredQuantity++;
UE_LOG(LogTemp, Warning, TEXT("After Interaction - StoredQuantity: %d"), ExistingItemData->StoredQuantity);
Destroy();
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Storage full of Meds: %d"), ExistingItemData->StoredQuantity);
}
}
else
{
GameInstance->ItemDataList.Add(ItemInfo);
ItemInfo.StoredQuantity++;
Destroy();
UE_LOG(LogTemp, Warning, TEXT("New item added to GameInstance."));
}
}
}
And then, I have my character class that has this function to heal:
void AMyCharacter::Heal()
{
UFPSGameInstance* GameInstance = Cast<UFPSGameInstance>(GetGameInstance());
if (GameInstance)
{
FItemData* ExistingItemData = nullptr;
FString HealItem = "Medikit";
//PROBLEM: what if someone wants to change the name of the Medikit??
for (FItemData& Data : GameInstance->ItemDataList)
{
if (Data.ItemName == HealItem)
{
ExistingItemData = &Data;
break;
}
}
if (ExistingItemData != nullptr)
{
if (ExistingItemData->StoredQuantity > 0)
{
ExistingItemData->StoredQuantity--;
Health += 10;
UE_LOG(LogTemp, Warning, TEXT("Used a medikit. New health: %d"), Health);
UE_LOG(LogTemp, Warning, TEXT("Used a medikit. New Quantity: %d"), ExistingItemData->StoredQuantity);
}
else
{
const int32 IndexToRemove = GameInstance->ItemDataList.Find(*ExistingItemData);
if (IndexToRemove != INDEX_NONE)
{
GameInstance->ItemDataList.RemoveAt(IndexToRemove);
}
UE_LOG(LogTemp, Warning, TEXT("Storage empty of Meds: %d"), ExistingItemData->StoredQuantity);
}
}
}
}
It all works perfectly in UE5.
But I was wondering if there is a more efficient way to implement this.