Inventory Management System

This section shows you how you can use the ObservedCollection<T> class to create an inventory management system.

In game development, an inventory system is crucial for managing a player's collection of items. A great way to keep track of these items is to use an observable collection.

Here's an example Item class to represent an item in the player's inventory:

public class Item
{
    public string Name { get; set; }
    public int Quantity { get; set; }

    public Item(string name, int quantity)
    {
        Name = name;
        Quantity = quantity;
    }
}

We will use an ObservedCollection to store all the items in the inventory and update the database whenever an item is picked up or dropped. This is accomplished through the InventoryManager class, which implements the inventory system:

using Observed;
using UnityEngine;

public class InventoryManager : MonoBehaviour
{
    // Create an observed collection to store the inventory items
    public ObservedCollection<Item> inventory = new ObservedCollection<Item>();

    // Subscribe to the collection's changes in the Awake method
    private void Awake()
    {
        inventory.Subscribe(UpdateInventoryDatabase);
    }

    // Add an item to the inventory and trigger the update in the inventory database
    public void AddItem(Item item)
    {
        // Add the item to the observed collection
        inventory.Add(item);
    }

    // Remove an item from the inventory and trigger the update in the inventory database
    public void RemoveItem(Item item)
    {
        // Remove the item from the observed collection
        inventory.Remove(item);
    }
}

A separate class, such as DatabaseManager, can be used to handle the updates to the database whenever there is a change to the inventory:

public class DatabaseManager : MonoBehaviour
{
    public InventoryManager inventoryManager;
    private void Awake()
    {
    // Subscribe to the inventory changes in the Awake method
    inventoryManager.inventory.Subscribe(UpdateInventory);
    }
    private void UpdateInventory(Item item, ChangeType action)
    {
        // Write code to update the inventory database with the changes made to the inventory
        // ...

        // Check if the action is "add"
        if (action == ChangeType.Added)
        {
            // Write code to add the item to the inventory database
            // ...
        }
        // Check if the action is "remove"
        else if (action == ChangeType.Removed)
        {
            // Write code to remove the item from the inventory database
            // ...
        }
    }
}

This example demonstrates how to use the AddItem and RemoveItem methods to update the inventory, and how to use the UpdateInventory method to handle updates to the database. This method can be modified to include the logic for updating the database, such as sending a request to a server or writing to a local file.

Last updated