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

Consider this code:

void loadData() {
    char* buffer = new char[1024];
    // some processing...
    if (someCondition()) {
        return; // leak!
    }
    delete[] buffer;
}

Apr 11, 2025
Read More
Tutorial

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

A shallow copy copies the values of member variables as-is. If your class has a pointer member, both the original and copy point to the same memory.

class Shallow {
public:
    int* data;

    Shallow(int val) {
        data = new int(val);
    }

    ~Shallow() {
        delete data;
    }
};

Apr 11, 2025
Read More
Tutorial

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

  • Lexing & Parsing: Tokenizing input and building an AST using recursive-descent parsing.
  • AST & Code Generation: Creating an AST that maps directly to LLVM IR, enabling advanced optimizations.
  • Optimization & Execution: Leveraging LLVM’s optimization passes and setting the stage for JIT compilation.
  • Enhance the DSL: Add support for variables, functions, and control flow constructs.
  • Improve Error Handling: Develop a robust error recovery strategy in your parser.
  • Integrate JIT Execution: Use LLVM’s ORC JIT to compile and run your DSL expressions dynamically.
  • Experiment with Optimizations: Explore custom optimization passes and advanced LLVM features available in 2025.

Feb 12, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • Using AJAX or Fetch API, JavaScript retrieves and updates data without reloading the page.
  • Example: Infinite scrolling on social media feeds.
  • Frameworks and libraries like React, Angular, and Vue.js make it easier to build Single Page Applications (SPAs).
  • Examples: Gmail, Netflix, Trello.

Dec 10, 2024
Read More

Discussion 0

Please sign in to join the discussion.

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