I am trying to create a stackable inventory system using a TArray. To check if i already have the same actor inside of my array before the item is added I’m using “.Contains” as the condition in my if statement, but that is getting ignored completely. What do i need to change to stop my if condition from getting ignored. I tried
auto Heal = Cast<AHealingItems>(Item);
if (Heal) {
bool bInSlot = Inventory.Contains(Heal);
if (bInSlot) {
printf("I am here!!!");
int32 HealIndex = Inventory.Find(Heal);
Heal->SetSlotIndex(HealIndex);
Heal->ItemAmount++;
Heal->Destroy();
}
else if (!bInSlot && Inventory.Num() < InventoryCapacity) {
Heal->SetSlotIndex(Inventory.Num());
Inventory.Add(Heal);
Heal->ItemAmount++;
Heal->SetItemState(EItemState::EIS_PickedUp);
}
else {
printf("Inventory is full!!");
}
}
auto Heal = Cast<AHealingItems>(Item); creates a brand new pointer. It can’t be in the array, because it didn’t exist earlier. Even if you have the same name of the pointer, it’s still a different pointer from what you had before.
You need to check some other parameter. For instance, an actor tag (add one to your AHealinlgItems class first).
bool bInSlot = false;
for (AActor* actor : Inventory)
{
if (actor->ActorHasTag(FName("Heal"))
{
bInSlot = true;
break;
}
}
I accidentally claimed this to be solved. I am not familiar with actor tags and every tutorial i see the person in the video is using an interface or doing something that is unnecessary for what im trying to do. Could you please explain how set up the actor tags because every way have tried is getting my if condition ignored. “AInGameItem” is the parent class to the actors that go into my inventory array.
void AMainCharacter::GetInGameItem(AInGameItem* Item) {
auto Weapon = Cast<AWeaponBase>(Item);
if (Weapon) {
Weapon->SetItemType(EItemType::EIT_NonStackable);
if(Inventory.Num() < InventoryCapacity && WeaponCTR < 2){
Weapon->SetSlotIndex(Inventory.Num());
Inventory.Add(Weapon);
Weapon->SetItemState(EItemState::EIS_PickedUp);
WeaponCTR++;
}
else { //if inventory is full
ReplaceWeapon(Weapon);
printf("Only 2 weapons in your inventory!!");
}
}
bool bInSlot = false;
for (AInGameItem* actor: Inventory){
if (actor->ActorHasTag(FName("Heal"))) {
bInSlot = true;
GEngine->AddOnScreenDebugMessage(-1,5.f,FColor::Cyan,"Stackable");
break;
}
else if(Inventory.Num() < InventoryCapacity) {
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Cyan, "NonStackable");
actor->SetSlotIndex(Inventory.Num());
Inventory.Add(actor);
break;
}
}
auto Ammo = Cast<AAmmoPickUps>(Item);
if (Ammo) {
PickUpAmmo(Ammo);
}
}
Do you have a blueprint derived from your cpp class? If yes, just find Tags in its details and add a tag you want.
If you’re only using cpp, you can call Tags.Add(FName("MyTag")); on BeginPlay(), is will add your tag to the actor when it’s spawned.
Actor tags are really useful, they can tell a lot about your actors without the need to Cast() etc.