Published on August 12, 2024By DeveloperBreeze

Unity Inventory System using Scriptable Objects

This snippet provides a basic structure for creating an inventory system using scriptable objects in Unity, which allows for easy data management and scalability.

1. Item Scriptable Object

Create a scriptable object for defining item properties.

using UnityEngine;

// Define the base item as a scriptable object
[CreateAssetMenu(fileName = "NewItem", menuName = "Inventory/Item")]
public class Item : ScriptableObject
{
    public string itemName;
    public Sprite icon;
    public bool isStackable;
    public int maxStackSize = 1;

    public virtual void Use()
    {
        Debug.Log($"Using {itemName}");
    }
}

2. Inventory System

A simple inventory system that can add, remove, and use items.

using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{
    public List<Item> items = new List<Item>();
    public int capacity = 20;

    public bool AddItem(Item item)
    {
        if (items.Count >= capacity)
        {
            Debug.Log("Inventory is full!");
            return false;
        }

        if (item.isStackable)
        {
            Item existingItem = items.Find(i => i.itemName == item.itemName);
            if (existingItem != null)
            {
                // Stack logic (if needed)
                Debug.Log($"Stacking {item.itemName}");
                return true;
            }
        }

        items.Add(item);
        Debug.Log($"{item.itemName} added to inventory.");
        return true;
    }

    public void RemoveItem(Item item)
    {
        if (items.Contains(item))
        {
            items.Remove(item);
            Debug.Log($"{item.itemName} removed from inventory.");
        }
    }

    public void UseItem(Item item)
    {
        if (items.Contains(item))
        {
            item.Use();
        }
    }
}

3. Inventory UI (Optional)

A basic setup for displaying the inventory items in the Unity UI.

using UnityEngine;
using UnityEngine.UI;

public class InventoryUI : MonoBehaviour
{
    public Inventory inventory;
    public GameObject inventoryPanel;
    public GameObject inventorySlotPrefab;

    void Start()
    {
        RefreshInventoryUI();
    }

    public void RefreshInventoryUI()
    {
        // Clear existing UI elements
        foreach (Transform child in inventoryPanel.transform)
        {
            Destroy(child.gameObject);
        }

        // Create new UI elements
        foreach (Item item in inventory.items)
        {
            GameObject slot = Instantiate(inventorySlotPrefab, inventoryPanel.transform);
            Image iconImage = slot.transform.GetChild(0).GetComponent<Image>();
            iconImage.sprite = item.icon;

            // Add more UI logic as needed (like item count for stackable items)
        }
    }
}

Usage Instructions

    • Create Items: In Unity, create new items by right-clicking in the Project window and selecting Create > Inventory > Item. Configure each item's properties, such as name and icon.

    • Add Inventory System: Attach the Inventory component to a GameObject in your scene (e.g., a player character).

    • Set Up Inventory UI: Create a UI panel with a Grid Layout Group to serve as the inventory panel. Use the InventoryUI script to manage the display. The inventorySlotPrefab should be a UI element with an Image component for the item icon.

    • Interaction Logic: Use methods like AddItem, RemoveItem, and UseItem in your game logic to interact with the inventory system.

Benefits of Using Scriptable Objects

  • Data Management: Scriptable objects allow you to manage item data independently from game logic, making it easier to update and maintain.

  • Reusability: You can create item templates and reuse them across different scenes and projects.

  • Performance: Scriptable objects reduce memory overhead compared to prefab-based systems since they are shared across instances.

This inventory system blueprint provides a flexible and extendable foundation for managing game items and inventories, ideal for RPGs, adventure games, or any project requiring complex item management.

Comments

Please log in to leave a comment.

Continue Reading: