DeveloperBreeze

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.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Avoiding Memory Leaks in C++ Without Smart Pointers

In this tutorial, you'll learn:

  • How memory leaks happen.
  • How to structure your code to avoid them.
  • A design pattern to manage dynamic memory safely (RAII without smart pointers).
  • A reusable ScopedPointer class to emulate unique_ptr in old C++.

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++

(3 + 4) * (5 - 2) / 2

The lexer (or tokenizer) converts a stream of characters into a sequence of tokens. Each token represents a logical unit, such as a number or operator.

Feb 12, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • With Node.js, JavaScript powers the back-end to handle databases, APIs, and server logic.
  • Examples: REST APIs, real-time collaboration tools like Google Docs.

JavaScript isn't limited to the browser anymore. It's being used in diverse domains:

Dec 10, 2024
Read More
Tutorial
python

Build a Multiplayer Game with Python and WebSockets

Serve the game interface using Flask.

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

if __name__ == "__main__":
    app.run(debug=True)

Dec 10, 2024
Read More
Tutorial
javascript

Advanced State Management in React Using Redux Toolkit

Use React.memo to prevent unnecessary re-renders in connected components:

import React from 'react';

const UserItem = React.memo(({ user }) => {
  return <li>{user.name}</li>;
});

Dec 09, 2024
Read More
Tutorial
php

Optimizing Performance in Laravel by Centralizing Data Loading

Add the following to the boot method of the service provider:

   public function boot()
   {
       view()->share('sharedData', app('sharedData'));
   }

Nov 16, 2024
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More
Tutorial
css

Advanced Flexbox Techniques: Creating Responsive and Adaptive Designs

  • Building Adaptive, Responsive Image Grids

Before diving into advanced techniques, it’s essential to quickly revisit the basics of Flexbox to ensure a solid foundation.

Sep 05, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

When JavaScript encounters an asynchronous operation, such as a setTimeout, it hands it off to the browser or Node.js runtime to handle. The Event Loop then continuously checks if the main call stack is empty. Once it is, the Event Loop pushes the callback from the asynchronous operation back onto the call stack for execution.

console.log('Start');

setTimeout(() => {
    console.log('Timeout');
}, 0);

console.log('End');

// Output:
// Start
// End
// Timeout

Sep 02, 2024
Read More
Tutorial
python

Getting Started with Pydantic: Data Validation and Type Coercion in Python

class Address(BaseModel):
    street: str
    city: str

class User(BaseModel):
    id: int
    name: str
    age: int
    address: Address

Pydantic allows you to define constraints on fields, such as minimum and maximum values:

Aug 29, 2024
Read More
Cheatsheet
javascript

React Performance Optimization Cheatsheet: Hooks, Memoization, and Lazy Loading

React Hooks allow you to use state and other React features in functional components. Some Hooks, like useMemo and useCallback, are specifically designed to optimize performance.

useMemo is used to memoize the result of a computation, preventing expensive calculations on every render. It re-computes the memoized value only when one of the dependencies has changed.

Aug 20, 2024
Read More
Tutorial
bash

Implementing RAID on Linux for Data Redundancy and Performance

  • Install mdadm:

On Debian/Ubuntu-based systems:

Aug 19, 2024
Read More
Tutorial
csharp

Developing a Real-Time Multiplayer Game with Unity and C#

This script allows the player to move forward and backward using the Vertical axis and rotate using the Horizontal axis. The IsOwner check ensures that only the player who owns the object can control it.

  • Save all your changes and go back to the main scene.
  • Press Play and use the NetworkManagerHUD to start as a Host, Client, or Server.
  • You should be able to control the player object and see it move on both the host and client.

Aug 14, 2024
Read More
Code
csharp

Unity Player Controller Blueprint

No preview available for this content.

Aug 12, 2024
Read More
Tutorial
mysql

Data Import and Export in MySQL

  • your_username: Your MySQL username.
  • your_database_name: The name of the database you want to export.
  • backup.sql: The file where the exported data will be saved.

To export a specific table from a database, use the following command:

Aug 12, 2024
Read More
Tutorial
mysql

How to Monitor MySQL Database Performance

  • Prometheus: Set up a MySQL exporter to collect metrics.
  • Grafana: Use Grafana to create custom dashboards and alerts based on Prometheus data.

Percona PMM is a free, open-source platform for managing and monitoring MySQL databases.

Aug 12, 2024
Read More
Tutorial
mysql

Viewing the Database Size and Identifying the Largest Table in MySQL

Execute the following query, replacing your_database_name with the name of your database:

SELECT table_schema AS "Database",
       ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)"
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
GROUP BY table_schema;

Aug 12, 2024
Read More
Code
csharp

Calculate Sum of Numbers in Array

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!