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
- Open Unity Hub and create a new Unity project.
- 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".
- Select an object in the scene.
- In the Inspector window, click on the "Tag" dropdown.
- Select "Add Tag" and enter "Pickup".
- Apply the tag to the object.
Step 3: Testing the System
- Add some objects with the "Pickup" tag to your scene.
- Play the scene in Unity.
- Click on a tagged object to pick it up.
- 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.