Compile error in TArray.Find(const ElementType &, int32 &)

Hi everyone,

I am working on a C++ implementation of the second part of Tom Looman’s Blueprint Inventory tutorial, with Blueprints subclassed to the custom C++ classes AInventoryActor and APickupActor. The original tutorial can be found at:

AFPSCharacter.h features the following TArray for the player’s inventory:

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Inventory")
    TArray<AInventoryActor*> InventoryItems;

In AFPSCharacter.cpp, I have a DropItem method that is defined as follows:

void AFPSCharacter::DropItem()
{
    if (InventoryItems.Num() > 0) // Don't do anything if the array is empty!
    {
        AInventoryActor *droppedItem = InventoryItems.Find(TSubclassOf<AInventoryActor>(), SelectedItem);
        
        UWorld* const World = GetWorld();
        if (World)
        {
            FActorSpawnParameters SpawnParams;
            SpawnParams.Instigator = Instigator;
            World->SpawnActor<APickupActor>(droppedItem->PickupClass, this->GetActorLocation() + FVector(0.0, 0.0, BaseEyeHeight), this->GetControlRotation(), SpawnParams);
        }
        
        InventoryItems.RemoveAt(SelectedItem);
    }
}

Unfortunately, there is a compiler error in InventoryItems.Find(TSubclassOf(), Selected Item) where it throws the error “No matching member for call to ‘Find’”. AFPSCharacter.cpp should know what AInventoryActor is since the line #include “InventoryActor.h” is found at the top, with all the other necessary #include statements. I can’t seem to figure out how to fix the problem, since the definition of TArray.Find(const ElementType &, int32 &) is somewhat confusing. The idea is to find the currently selected inventory item (which is the item at the index currently selected), spawn it in the world, and remove it from the inventory. What am I missing here?

#Solution

What happens if you do this

//Find Item
int32 FoundIndex = InventoryItems.Find(SelectedItem);

//was item found?
if(InventoryItems.IsValidIndex(FoundIndex)
{
  //your other code....

  //Remove found item
  InventoryItems.RemoveAt(FoundIndex);
}

I do that all the time and it works just fine :slight_smile:

#:heart:

Rama

Thanks Rama,

I have also found an additional solution that takes advantage of TArray’s overloading of the [] operator. So the Inventory.Find line is replaced with:

AInventoryActor *droppedItem = InventoryItems[SelectedItem];

Now, I just need to move onto making the inventory system stackable by leveraging your solution to the TArray.Find problem…