Hi,
I was wondering how best to handle an array of structs. Basically, I have a struct that stores information about n item in the inventory, I then store this in an array, but i noticed that the standard array functions dont work as it cant compare two structs. I am assuming I need to create a custom function too compare the properties of the structs and then use tthat when trying too add/remove. i.e. iterate over the array and compare each one before determining if it can be added or not.
I was just wondering if this is the best way?
Also is there a way to make sure each instance of the struct has a uniqueID, i.e. when the struct is established it gets a unique number.
Hey John,
can you provide the criteria which allows the struct to be added into the Array?
If the criteria is that you don’t want to put one struct twice into the Array you can simply use the AddUnique Method of TArray.
If the criteria is more complex I would suggest you to write an overloaded operator for your struct which compares them.
If you don’t know how to do this:
bool operator==(const FStructType& OtherStruct)
{
return //...criteria
}
To give your Struct Unique IDs:
USTRUCT()
struct FStructType
{
GENERATED_BODY()
uint32 UniqueID;
FStructType()
{
static uint32 ID = 0;
UniqueID = ID++;
}
//Maybe you need this???
bool operator==(const FStructType& Type)
{
return UniqueID == Type.UniqueID;
}
}
I hope I could help you
If not, I’m glad to give some more Input
Greetings
No I didn’t have the override for the ==, but I have added it now. However, it is still not letting me use stuff like Array.AddUnique(); giving the reason binary operator == not found that takes left hand of InventoryItem. Am I doinf something wrong in the way I add the operator to the struct?
USTRUCT()
struct FInventoryItem
{
GENERATED_USTRUCT_BODY()
// Unique ID for the item
UPROPERTY(EditDefaultsOnly, Category = Item)
int32 ItemID;
// Item name
UPROPERTY(EditDefaultsOnly, Category = Item)
FText ItemName;
// Item class to spawn
UPROPERTY(EditDefaultsOnly, Category = Item)
TSubclassOf<AActor> ItemClass;
// Item image to be displayed within the inventory
UPROPERTY(EditDefaultsOnly, Category = Item)
TAssetPtr<UTexture2D> ItemImage;
// Flag to capture if the item has been selected
UPROPERTY(EditDefaultsOnly, Category = Item)
bool bIsSelected;
// The slot the item is stored in
UPROPERTY(EditDefaultsOnly, Category = Item)
int32 InSlot;
bool operator==(const FInventoryItem& InventoryItem)
{
return ItemID == InventoryItem.ItemID
&& ItemName.EqualTo(InventoryItem.ItemName)
&& ItemClass == InventoryItem.ItemClass;
}
};
Thanks for the help
Ok. It seems you have to add const after your Argumentlist.
bool operator==(const FInventoryItem& OtherItem) const
{
return ...
}
This worked in my project
Good luck
That worked perfect, thank you so much for your help
No Problem
Good luck and have fun