UnrealScripterAI
Discord ↗
Link Copied to Clipboard
×
"Create a grid inventory system"
// Grid Inventory System UCLASS() class UGridInventory : public UObject { GENERATED_BODY() public: UGridInventory(); UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Inventory") int32 GridRows; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Inventory") int32 GridColumns; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Inventory") TArray<UInventoryItem*> InventoryItems; UFUNCTION(BlueprintCallable, Category = "Inventory") bool AddItemToInventory(UInventoryItem* Item); UFUNCTION(BlueprintCallable, Category = "Inventory") bool RemoveItemFromInventory(UInventoryItem* Item); UFUNCTION(BlueprintCallable, Category = "Inventory") UInventoryItem* GetItemAtGridPosition(int32 Row, int32 Column); private: int32 GetInventoryIndex(int32 Row, int32 Column) const; }; UGridInventory::UGridInventory() { GridRows = 5; GridColumns = 5; InventoryItems.SetNumZeroed(GridRows * GridColumns); } bool UGridInventory::AddItemToInventory(UInventoryItem* Item) { for (int32 i = 0; i < InventoryItems.Num(); i++) { if (InventoryItems[i] == nullptr) { InventoryItems[i] = Item; return true; } } return false; } bool UGridInventory::RemoveItemFromInventory(UInventoryItem* Item) { for (int32 i = 0; i < InventoryItems.Num(); i++) { if (InventoryItems[i] == Item) { InventoryItems[i] = nullptr; return true; } } return false; } UInventoryItem* UGridInventory::GetItemAtGridPosition(int32 Row, int32 Column) { int32 Index = GetInventoryIndex(Row, Column); if (Index != INDEX_NONE) { return InventoryItems[Index]; } return nullptr; } int32 UGridInventory::GetInventoryIndex(int32 Row, int32 Column) const { if (Row >= 0 && Row < GridRows && Column >= 0 && Column < GridColumns) { return Row * GridColumns Column; } return INDEX_NONE; }