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

  1. 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.
  2. Add Inventory System: Attach the Inventory component to a GameObject in your scene (e.g., a player character).
  3. 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.
  4. 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.

Related Posts

More content you might like

Tutorial

Avoiding Memory Leaks in C++ Without Smart Pointers

What’s wrong? If someCondition() returns true, buffer is never deallocated.

void loadData() {
    char* buffer = new char[1024];
    try {
        if (someCondition()) {
            throw std::runtime_error("Something went wrong");
        }
        // more code...
    } catch (...) {
        delete[] buffer;
        throw;
    }
    delete[] buffer;
}

Apr 11, 2025
Read More
Tutorial

Deep Copy in C++: How to Avoid Shallow Copy Pitfalls

  • Copy Constructor
  • Copy Assignment Operator
  • Destructor

You must implement all three. This is called the Rule of Three.

Apr 11, 2025
Read More
Tutorial

Implementing a Domain-Specific Language (DSL) with LLVM and C++

Header: Lexer.h

#ifndef DSL_LEXER_H
#define DSL_LEXER_H

#include <string>
#include <vector>

enum class TokenType {
    Number,
    Plus,
    Minus,
    Asterisk,
    Slash,
    LParen,
    RParen,
    EndOfFile,
    Invalid
};

struct Token {
    TokenType type;
    std::string text;
    double value; // Only valid for Number tokens.
};

class Lexer {
public:
    Lexer(const std::string& input);
    Token getNextToken();

private:
    const std::string input;
    size_t pos = 0;
    char currentChar();

    void advance();
    void skipWhitespace();
    Token number();
};

#endif // DSL_LEXER_H

Feb 12, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • Libraries like Three.js and Babylon.js enable building browser-based games.
  • Example: Interactive 3D experiences.

JavaScript continues to evolve with yearly updates. Features like async/await, optional chaining, and tools like TypeScript are shaping the future of web development.

Dec 10, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!