The reason your code is crashing is because your Inventory class and instances are not being tracked by the UObject system in UE4. This means that the pointers to your objects in the TArray ItemsArray
can become invalid.
You should change your inventory class declaration to be a UStruct instead, and look like this:
USTRUCT(BlueprintType)
struct GRAVITYGAME_API FInventory
{
GENERATED_BODY()
void AddItemToInventory(AUsableItem* ItemToInsert);
void RemoveItemFromInvetory(AUsableItem* ItemToRemove);
// An array which stores the picked up items.
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Array)
TArray<AUsableItem*> ItemsArray;
};
(sorry if the formatting was messed up by Answerhub)
You don’t need a constructor. There’s nothing for it to do.
This: Inventory* PlayerInventory;
needs to become this: FInventory PlayerInventory;
You should almost never use the ‘new’ keyword in UE4, except in certain cases such as dealing with the lower-level parts of Slate. There’s no reason for you to create an Inventory object as a raw pointer and create it by hand. It’s not accomplishing anything, it makes things more complicated, and it prevents the UE4 object system from working with it.
By changing it to be a struct (specifically, a UStruct) instead of a pointer to a raw C++ class, it will correctly work as a UPROPERTY, the pointers to UObjects within the inventory array will be tracked correctly by UE4, and you will not need to do manual memory management.
As an example of why you shouldn’t have been doing the manual memory management by hand: your game was leaking every Inventory object you created, because you did not destruct it properly. Also, it would have not worked correctly when creating new instances of your AMainCharacter class from Blueprint subclasses in the editor, since it didn’t deal with copying/CDO correctly.
Also, the UPROPERTY macro you were using in your Inventory class was doing nothing – it only does stuff if you have a GENERATED_BODY() and the class or struct is a UCLASS or a USTRUCT.
Hope that fixes it for you!