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

Let’s build a small ScopedPointer class.

template <typename T>
class ScopedPointer {
private:
    T* ptr;

public:
    explicit ScopedPointer(T* p = nullptr) : ptr(p) {}

    ~ScopedPointer() {
        delete ptr;
    }

    T& operator*() const { return *ptr; }
    T* operator->() const { return ptr; }
    T* get() const { return ptr; }

    void reset(T* p = nullptr) {
        if (ptr != p) {
            delete ptr;
            ptr = p;
        }
    }

    // Prevent copy
    ScopedPointer(const ScopedPointer&) = delete;
    ScopedPointer& operator=(const ScopedPointer&) = delete;
};

Apr 11, 2025
Read More
Tutorial

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

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

class String {
private:
    char* buffer;

public:
    String(const char* str) {
        buffer = new char[strlen(str) + 1];
        strcpy(buffer, str);
    }

    // Copy constructor
    String(const String& other) {
        buffer = new char[strlen(other.buffer) + 1];
        strcpy(buffer, other.buffer);
    }

    // Assignment operator
    String& operator=(const String& other) {
        if (this != &other) {
            delete[] buffer;
            buffer = new char[strlen(other.buffer) + 1];
            strcpy(buffer, other.buffer);
        }
        return *this;
    }

    ~String() {
        delete[] buffer;
    }

    void print() const {
        std::cout << buffer << std::endl;
    }
};

Apr 11, 2025
Read More
Tutorial

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

For this tutorial, we’ll create a DSL for evaluating mathematical expressions. Our language will support:

  • Numeric literals (e.g., 42, 3.14)
  • Basic arithmetic operators: +, -, *, /
  • Parentheses for grouping expressions

Feb 12, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

JavaScript plays a pivotal role in shaping the dynamic and interactive experiences we enjoy on the web today. Here's a deeper dive into its significance:

JavaScript is the engine behind the dynamic behavior of modern websites. It works alongside HTML (structure) and CSS (style) to create a complete web experience.

Dec 10, 2024
Read More
Tutorial
python

Build a Multiplayer Game with Python and WebSockets

class TicTacToe:
    def __init__(self):
        self.board = [" "] * 9
        self.current_turn = "X"

    def make_move(self, position):
        if self.board[position] == " ":
            self.board[position] = self.current_turn
            if self.check_winner():
                return f"{self.current_turn} wins!"
            self.current_turn = "O" if self.current_turn == "X" else "X"
            return "Next turn"
        return "Invalid move"

    def check_winner(self):
        win_conditions = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ]
        for condition in win_conditions:
            if self.board[condition[0]] == self.board[condition[1]] == self.board[condition[2]] != " ":
                return True
        return False

We’ll use the websockets library to handle communication between players.

Dec 10, 2024
Read More
Tutorial
javascript

Advanced State Management in React Using Redux Toolkit

src/
├── app/                # Global app configuration
│   └── store.js        # Redux store configuration
├── features/           # Feature slices
│   ├── users/          # User management feature
│   │   ├── components/ # UI components for users
│   │   ├── usersSlice.js # Redux slice for users
├── hooks/              # Custom hooks
│   └── useAppSelector.js # Typed hooks for Redux state
└── index.js            # Entry point

Redux Toolkit revolves around three key concepts:

Dec 09, 2024
Read More
Tutorial
php

Optimizing Performance in Laravel by Centralizing Data Loading

Consider an application where you need to frequently access:

  • Global Limits: Values such as maximum uploads or API rate limits.
  • User Permissions: Whether a user has specific privileges like admin access.
  • Feature Toggles: Configuration to enable or disable specific features dynamically.

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

This approach is useful for creating layouts with both horizontal and vertical alignment.

Flexbox can be used to create responsive image galleries that adapt to screen size.

Sep 05, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

Optimizing JavaScript performance involves both improving the efficiency of your code and reducing its memory footprint. Here are some common techniques:

Reflows and repaints are processes that occur when the layout or appearance of the web page changes. These processes can be expensive, especially if they are triggered frequently.

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.lazy allows you to lazy-load components, and Suspense provides a fallback while the component is being loaded.

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

export default App;

Aug 20, 2024
Read More
Tutorial
bash

Implementing RAID on Linux for Data Redundancy and Performance

   sudo cat /proc/mdstat

You can add more disks to an existing RAID array to increase its capacity.

Aug 19, 2024
Read More
Tutorial
csharp

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

  • In the Hierarchy window, right-click and create a new 3D Object > Plane to serve as the ground.
  • Create a 3D Object > Cube to act as the player character.
  • Position the cube above the plane so that it is ready to fall due to gravity.
  • Add a Camera and Light to the scene if they are not already present.
  • Right-click in the Hierarchy and create an empty GameObject. Name it "NetworkManager."
  • Add the NetworkManager component by clicking Add Component and searching for "NetworkManager."
  • Also, add the NetworkManagerHUD component to provide basic controls for starting and stopping the server or 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

To export only the database schema without data, use the --no-data option:

mysqldump -u your_username -p --no-data your_database_name > schema_backup.sql

Aug 12, 2024
Read More
Tutorial
mysql

How to Monitor MySQL Database Performance

Monitoring MySQL database performance is crucial for maintaining efficient and reliable database operations. By keeping an eye on performance metrics, you can identify bottlenecks, optimize queries, and ensure that your database is running smoothly. This tutorial will cover various tools and techniques for monitoring MySQL performance.

  • Basic understanding of MySQL and SQL operations.
  • Access to a MySQL server.
  • Familiarity with command-line tools and basic server administration.

Aug 12, 2024
Read More
Tutorial
mysql

Viewing the Database Size and Identifying the Largest Table in MySQL

This query will output the largest table in the specified database along with its size.

After executing these queries, you'll have a clear understanding of the total size of your database and which table is consuming the most space. This information can help you make informed decisions about database optimization and storage planning.

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!