How can I make my basic inventory / healing system more efficient? C++

Yes there are ways to improve this code.

Firstly, I haven’t seen the FItemData but from your code it looks like it was meant to be used for as some sort of inventory data (storing the name of the item and the count of items that player holds). If that’s right there is basically no need to have a property of that type for the actor representation of the item. What you can do here, is that instead of TArray you use a TMap<TSubclassOf, FItemData>
And use UClass of your actors as the map key. Then if you want to check if such item exists in ItemDataList ( or technically ItemDataMap), you use Contains() method of the map. This itself reduces your array search average complexity of O(N/2) to O(1).
Also with this method if you change your item name it won’t affect the functionality of your code.

Also I would personally encapsulate the functionality of inventory in an actor component and attach it directly to the player. Holding this kind of stuff in game instance object isn’t really clean. It works for a small project and on a single player game but in the long run it will make your game instance code messy and if you decide to go for multiplayer you will have some massive refactoring to do.

Lastly, your game instance is set in the project settings. it is also supposed to last from when your game starts until when you quit the game. There is no need to use Cast on it. Just use static_cast and you should be fine. In this particular instance the difference is going to be virtually non-existent but if you end up doing a few hundred Casts every frame it will start to impact your performance.

1 Like