Trouble using TSubobjectPtr and TSubclassOf

I’m trying to put together an inventory system. I have most of the basics down but I’m trying to make things more generic by having an item superclass and specific types of items as subclasses.

In general, here is what I have:

class AItem : public AActor

class AWeapon : public AItem

class AConsumable : public AItem

and on the character I have:

TArray< AItem* > Inventory;

What I would have thought would have been the way to go would be to use TSubobjectPtr or TSubclassOf. Based on the info I found when searching was that TSubobjectPtr is what I want since I want these to be actual items, not representations of the types of items I have. Meaning, while in game you pick up an item (could be a consumable or a weapon) and that goes into this array. I have tried a few things and nothing seems to be working.

What I need help with is:

  • Should I just use it like this or should I be using TSubobjectPtr?
  • If so, what is the correct syntax to do this?

TSubobjectPtr is for pointers to components, and as of UE4.6, it will be deprecated, so in the future you can use regular pointers for components.

but your inventory is full of actor references, not components, so you can use regular pointers like you are doing, but every item in your inventory will need to be an instance spawned into the world.

or you can use TSubclassOf to store classes to spawn from. any items that have values changed from its default values can be initialized from a struct.

storing a list of structs that contain the class type and custom init values for an item is cheaper than spawning the items into the level and storing a pointer to the item.

if your game items are always the same stats for every play through, you could store all of the initialization structs in a .csv spread sheet, then in your array you can just store integers that represent the ItemID.

@Omnicypher

“storing a list of structs that contain the class type and custom init values for an item is cheaper than spawning the items into the level and storing a pointer to the item.”

+1 for great advice!

When items are in inventory they should just be abstract data, if for no other reason than you dont have to worry about what their world location is in relation to their owner and whether they will go out of network replication scope or some crazyness like that

Actors are also very expensive, even when invisible, pure USTRUCT data is free by comparison :slight_smile:

Rama