88 lines
2.4 KiB
C#
88 lines
2.4 KiB
C#
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
|
|
public class Inventory : MonoBehaviour
|
|
{
|
|
public int maxCapacity = 20;
|
|
public Dictionary<string, int> items = new();
|
|
public List<InventoryEntry> startingItems; //List for inspector
|
|
private int gold;
|
|
public int Gold
|
|
{
|
|
get { return gold; }
|
|
set { gold = Mathf.Max(0, value); }
|
|
}
|
|
|
|
void Start()
|
|
{
|
|
// Initialize inventory with starting items
|
|
foreach (var entry in startingItems)
|
|
{
|
|
AddItem(entry.itemName, entry.quantity);
|
|
}
|
|
}
|
|
// 'virtual' allows this method to be overridden by subclasses like PlayerInventory
|
|
public virtual void AddItem(string itemName, int quantity)
|
|
{
|
|
// Handle Gold as a special
|
|
if (itemName == "Gold")
|
|
{
|
|
Gold += quantity;
|
|
Debug.Log($"Added {quantity} Gold. Total: {Gold}");
|
|
return; // Stop here, don't add Gold to the items dictionary
|
|
}
|
|
if (items.ContainsKey(itemName))
|
|
{
|
|
items[itemName] += quantity;
|
|
}
|
|
else
|
|
{
|
|
if (items.Count < maxCapacity)
|
|
{
|
|
items[itemName] = quantity;
|
|
}
|
|
else
|
|
{
|
|
Debug.Log("Inventory is full. Cannot add: " + itemName);
|
|
return;
|
|
}
|
|
}
|
|
Debug.Log($"Added {quantity} {itemName}(s). Total: {items[itemName]}");
|
|
}
|
|
|
|
public void RemoveItem(string itemName)
|
|
{
|
|
items.Remove(itemName);
|
|
}
|
|
public int GetItemCount(string itemName)
|
|
{
|
|
return items.ContainsKey(itemName) ? items[itemName] : 0;
|
|
}
|
|
public string GetInventoryContentsAsString()
|
|
{
|
|
// Use a StringBuilder for efficient string creation
|
|
StringBuilder sb = new StringBuilder();
|
|
sb.AppendLine("--- INVENTORY ---");
|
|
|
|
// Add the Gold amount
|
|
sb.AppendLine($"Gold: {Gold}");
|
|
sb.AppendLine(); // Add a blank line
|
|
|
|
// Check if there are any items
|
|
if (items.Count == 0)
|
|
{
|
|
sb.AppendLine("No items.");
|
|
}
|
|
else
|
|
{
|
|
// Loop through the items dictionary and add each one to the string
|
|
foreach (KeyValuePair<string, int> item in items)
|
|
{
|
|
sb.AppendLine($"{item.Key}: {item.Value}");
|
|
}
|
|
}
|
|
|
|
return sb.ToString();
|
|
}
|
|
} |