Violation Error on Add to Tarray
I am trying to implement an inventory system into my game. I have made an items class which inherits from AActor, a Character class and an inventory class.
The Item is passed as a pointer to a function on
All the AddItemToInventory does is call the Add method on the
When I attempt to perform this action I get an Access Violation error:
asked Jan 18 '16 at 05:43 AM in C++ Programming
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
You should change your inventory class declaration to be a UStruct instead, and look like this:
(sorry if the formatting was messed up by Answerhub)
You don't need a constructor. There's nothing for it to do.
needs to become this:
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!
Follow this question
Once you sign in you will be able to subscribe for any updates here