Menu
CoddyTech

Recap: Interact Key

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 9 of 50.

challenge icon

Challenge

Easy

Give the player an interact key. The arrows walk the Player (Mover.cs, ready), and Space uses the nearest thing within reach that can be used. Write the parts:

  • IInteractable: an interface with one method, void Interact().
  • Door: each use swings it open or shut. Opening turns it 90 degrees around y and logs Door opened; closing turns it back and logs Door closed.
  • Chest: the first use logs Found 5 coins (its coins, which the Inspector sets) and empties it. Every later use logs The chest is empty.
  • Lever: each use switches bridge (a GameObject the Inspector sets, hidden at the start) on or off, and logs Lever pulled.
  • Interactor, on the Player: when Space is pressed (read it with the Input System's Keyboard.current), find the colliders within reach (1.5) with Physics.OverlapSphere, and call Interact() on the one that has an IInteractable and whose position is nearest to the player. With nothing in reach, nothing happens.

Press Play, walk around and use everything, then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;

// Space uses the nearest thing within reach.
public class Interactor : MonoBehaviour
{
    public float reach = 1.5f;
}

All lessons in Game Architecture in Unity