Recap: Interact Key
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 9 of 50.
Challenge
EasyGive 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 logsDoor closed. - Chest: the first use logs
Found 5 coins(itscoins, which the Inspector sets) and empties it. Every later use logsThe chest is empty. - Lever: each use switches
bridge(a GameObject the Inspector sets, hidden at the start) on or off, and logsLever pulled. - Interactor, on the Player: when Space is pressed (read it with the Input System's
Keyboard.current), find the colliders withinreach(1.5) withPhysics.OverlapSphere, and callInteract()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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types