I’m trying to build an inventory class that holds references to items, but whenever I try to add an item reference to the TArray the game crashes. Do I need to initialize my array somehow? Relevant code is below. Please let me know what I’m doing wrong, and the correct way to approach this.
// Item is clicked on in game
void ATDSItem::ItemOnClicked(UPrimitiveComponent* ClickedComponent)
{
// Get reference to local character
ATDSCharacter* myChar = Cast<ATDSCharacter>(GetWorld()->GetFirstPlayerController()->GetCharacter());
// Pickup this item
myChar->PickupItem(this);
}
// Pick up the item that was clicked on to player inventory
void ATDSCharacter::PickupItem(ATDSItem* Item)
{
if (Item)
{
bool bAdded = PlayerInventory->AddItem(Item);
Item->SetItemLocation(EItemLocation::InInventory);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, (FString("Picked up item: ") + Item->Name));
}
}
//from ATDSInventory.h
UPROPERTY(EditAnywhere, Category = Inventory)
TArray<class ATDSItem*> Items;
// Add the item to inventory
bool ATDSInventory::AddItem(ATDSItem* Item)
{
if (Item)
{
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, (FString(Item->Name)));
Items.Add(Item); // Crashes here with an access violation
return true;
}
else
{
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Yellow, (FString("Item null")));
return false;
}
}
It’s not null, as it crashes inside PlayerInventory->AddItem(Item); call at the line 32.
I’ve experienced some problems with TArray in the past as well, some of the properties were making troubles somehow… not sure how i fixed that. But it surely hard to debug in development build.
Non-virtual function calls don’t actually use the object pointer at the time of the function call (X->Foo()), they use it the first time a member variable accessed. Without seeing the header it’s difficult to tell, but if ATDSInventory::AddItem is non-virtual then the first time it actually accesses a member variable (and would crash from a NULL this pointer) is when it accesses the ITems array.
Here is a simple C++ test application that demonstrates this
Yes. In the debug trace “this” the PlayerInventory is null. So in my Character class I have ATDSInventory* PlayerInventory; which I’m looking at now and realizing how not-smart that was because I actually wanted a new instance there. The thing is, I only added that * because it wont let me compile ATDSInventory PlayerInventory;
Is there some other syntax for creating an instance of an AActor class?
That did the trick!
Well, for some reason there’s nothing to mark as an answer on the page, but thanks so much for helping me out. You guys are both awesome. Props to both of you.