Opening Drawers and Cupboards with Specific Keys in Unity

In this tutorial, we'll create a simple interactive system in Unity where drawers and cupboards can be opened using a specific key. This system will allow the player to interact with objects in the scene by pressing a designated key to open and close them.

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 drawers, cupboards, or any objects you want to interact with.

Implementing the Interactive System

Step 1: Create an Interactive Script

'InteractiveObject.cs'

using UnityEngine;

public class InteractiveObject : MonoBehaviour
{
    public KeyCode interactionKey;
    public GameObject openState;
    public GameObject closedState;

    private bool isOpen = false;

    void Update()
    {
        if (Input.GetKeyDown(interactionKey))
        {
            ToggleObjectState();
        }
    }

    void ToggleObjectState()
    {
        isOpen = !isOpen;
        openState.SetActive(isOpen);
        closedState.SetActive(!isOpen);
    }
}

Step 2: Set Up Object States

  1. Create two empty GameObjects as child objects of each drawer or cupboard. Name one "OpenState" and the other "ClosedState".
  2. Set the initial positions of these child objects to represent the open and closed states of the drawer or cupboard.
  3. Assign these child objects to the 'openState' and 'closedState' variables in the 'InteractiveObject.cs' script.

Step 3: Assign Interaction Key

  1. Select the object in the scene with the 'InteractiveObject.cs' script attached.
  2. In the Inspector window, set the 'interactionKey' variable to the desired KeyCode (e.g., KeyCode.E for the "E" key).

Step 4: Testing the System

  1. Play the scene in Unity.
  2. Approach the drawers or cupboards.
  3. Press the designated key (e.g., "E") to open and close them.

Conclusion

You've successfully implemented an interactive system in Unity that allows drawers and cupboards to be opened and closed using a specific key. This system can be expanded further by adding animations, sound effects, or more complex interactions to enhance the player experience. Feel free to experiment and add additional features to make your interactive objects even more engaging.

Suggested Articles
Tutorial for Opening a Door with a Key in Unity
Interacting with Objects in Unity Game
Making Inventory and Item Crafting System in Unity
Creating Interactive Objects in Unity
A Guide to Integrating Nintendo Controller with Unity
Creating a Traffic Simulator in Unity
Save and Load Logic for Unity