So I want to create an inventory system and be able to pick up item and store them into my inventory array: TArray<AItem*> ItemList;
InteractInterface.h:
#pragma once
#include “CoreMinimal.h”
#include “UObject/Interface.h”
#include “InteractInterface.generated.h”
UINTERFACE(MinimalAPI)
class UInteractInterface : public UInterface
{
GENERATED_BODY()
};
/**
*
*/
class RPGPROJECT_API IInteractInterface
{
GENERATED_BODY()
// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Interact")
void Interact();
UFUNCTION()
virtual void InteractPure();
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Interaction")
class AItem* GetItem();
};
I set overlappingitems in character.h:
FORCEINLINE void SetOverlappingItem(AItem* Item) { OverlappingItem = Item; }
And execute it in item.cpp:
void AItem::OnSphereOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
APlayerCharacter* PlayerCharacter = Cast(OtherActor);
if (PlayerCharacter)
{
PlayerCharacter->SetOverlappingItem(this);
}
}
item.cpp:
AItem* AItem::GetItem_Implementation()
{
return this;
}
PickUp function in character class:
void APlayerCharacter::PickUp()
{
if (OverlappingItem)
{
TArray<AActor*> OverlappingActors;
this->GetOverlappingActors(OverlappingActors, TSubclassOf());
for (auto& OverlappingActors : OverlappingActors)
{
if (OverlappingActors->GetClass()->ImplementsInterface(UInteractInterface::StaticClass()))
{
AItem* ItemToAdd = IInteractInterface::Excute_GetItem(OverlappingActors);
if (ItemToAdd)
{
AddToIntentory(ItemToAdd);
IInteractInterface::Execute_Interact(OverlappingActors);
}
}
}
}
}