Download

Best way to code an inventory-typed system?

So I learned how to use TMaps to create an inventory, but it was a much simpler type of inventory.

Basically it was like this:

TMap<FString, int32> Inventory;
TMap<FString, UTexture2D> Icon;

And I combined these TMaps to create a grid like system like so: FString name, int32 quantity, UTexture icon;

However, now I need to store more complex items in my inventory. I need to store variables such as name, cost, texture, mesh, and possibly other stuff. I basically need to put a tmap in a tmap in another tmap, and I don’t think that’s possible.

So, what is the best way to code an inventory system, like let’s say starcraft 2?

Instead of making several TMaps why not make a struct or class (Actor) of Items ?
Class Actor named Item which will hold Mesh, Texture, Cost, Name, Durability and so on.

Then have a TMap<FString, Item> Inventory

It’s way I approach in mine, tho, I use TArray

Well to be honest, I don’t know why. The book I’m using to learn UE4 says Arrays can be slower than TMaps, and I don’t want to make a habit of using methods that are inefficient.

Learn about UDataAsset… You won’t regret it.

Dictionaries are generally faster than arrays because you are mapping values to a key and searching in it is always a constant if my memory does not fail me. But dictionaries are not always the best solution. For example looping through it is harder. Another bad thing is, you can get collisions if not implemented properly.

Anyway both are cool to use.

TMaps might be faster, but practically speaking unless your TArray is gigantic or you are accessing many many times per tick, its generally insignificant. You can also keep it sorted like a BinaryHeap and use binary search.

I generally go with TArrays because they can be UPROPERTYs, which can save you from some nasty memory bugs and make debugging in the editor really easy.

The general rule in C++ is not to optimize prematurely if it can cost you future headaches, let the profiler guide you if and when you get CPU bound.