Learn How to Implement Pick Up and Drop in Your First Person Unity 3D Game

Learn How to Implement Pick Up and Drop in Your First Person Unity 3D Game

Here is a basic script that you can use to pick up and drop objects in Unity and allow you to drop the object whenever you want by using a different input key for dropping the object.:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PickUpObject : MonoBehaviour
{
    public GameObject objectToPickUp;
    public GameObject objectInHand;

    private bool objectIsPickedUp;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            PickUpObject();
        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            DropObject();
        }
    }

    void PickUpObject()
    {
        objectToPickUp.GetComponent<Rigidbody>().useGravity = false;
        objectToPickUp.transform.position = objectInHand.transform.position;
        objectToPickUp.transform.parent = objectInHand.transform;
        objectIsPickedUp = true;
    }

    void DropObject()
    {
        objectToPickUp.transform.parent = null;
        objectToPickUp.GetComponent<Rigidbody>().useGravity = true;
        objectIsPickedUp = false;
    }
}



To use this script, do the following:

  1. Attach the script to your first person player object.
  2. In the Inspector window, drag the object that you want to be able to pick up and drop into the "Object To Pick Up" field.
  3. Create an empty GameObject and place it in the hand of your first person player model. This will be the "Object In Hand" GameObject that the picked up object will be parented to. Drag this GameObject into the "Object In Hand" field in the Inspector window.

This script will allow you to pick up and drop objects using the "E" key. You can customize the key by changing the input in the Input.GetKeyDown function.