Pick and Drop System Without Inventory in Unity

In this tutorial, we'll create a simple pick-and-drop system in Unity without using an inventory system. This system will allow the player to pick up objects from the environment and drop them at a different location.

Prerequisites

  • Unity Hub installed
  • Unity Editor (version 2019 or later)
  • Basic knowledge of C#

Setting Up the Project

  1. Open Unity Hub and create a new Unity project.
  2. Set up your scene with a player character and some objects to interact with.

Implementing the Pick and Drop System

Step 1: Create a Pickup Script

using UnityEngine;

public class Pickup : MonoBehaviour
{
    private Transform heldObject;
    private Vector3 offset;

    void Update()
    {
        if (heldObject != null)
        {
            MoveHeldObject();
            CheckDrop();
        }
        else
        {
            CheckPickup();
        }
    }

    void MoveHeldObject()
    {
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        heldObject.position = new Vector3(mousePosition.x + offset.x, mousePosition.y + offset.y, 0);
    }

    void CheckPickup()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
            if (hit.collider != null && hit.collider.CompareTag("Pickup"))
            {
                heldObject = hit.transform;
                offset = heldObject.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);
            }
        }
    }

    void CheckDrop()
    {
        if (Input.GetMouseButtonDown(1))
        {
            heldObject = null;
        }
    }
}

Step 2: Add Tags to Pickup Objects

Tag the objects you want the player to be able to pick up with the tag "Pickup".

  1. Select an object in the scene.
  2. In the Inspector window, click on the "Tag" dropdown.
  3. Select "Add Tag" and enter "Pickup".
  4. Apply the tag to the object.

Step 3: Testing the System

  1. Add some objects with the "Pickup" tag to your scene.
  2. Play the scene in Unity.
  3. Click on a tagged object to pick it up.
  4. Right-click to drop the held object.

Conclusion

You've successfully implemented a simple pick-and-drop system without using an inventory in Unity. This system allows the player to interact with objects in the scene by picking them up and dropping them at different locations. Feel free to expand upon this system by adding features like object snapping, object rotation, or more complex interactions.

Suggested Articles
Coding a Simple Inventory System With UI Drag and Drop in Unity
Making Inventory and Item Crafting System in Unity
Creating Collectibles and Power-ups in Unity
Opening Drawers and Cupboards with Specific Keys in Unity
Interacting with Objects in Unity Game
Creating a Simple 2D Bullet System in Unity
Built-in Way of Working with JSON in Unity Code