Recap: Nearest in Reach
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 11 of 64.
This chapter used interfaces so one script can work with things that share nothing but a method. The interact key now picks the nearest of them.
Challenge
EasySpace should use the nearest thing, not the first.
- In
Interactor, before the loop, addIInteractable nearest = null;andfloat best = Mathf.Infinity;. - In the loop, keep any thing whose
Vector3.Distanceto the player is belowbest, with its distance. - After the loop, call
nearest.Interact()ifnearestis not null.
Press Play, stand between the chest and the lever and press Space: the lever is pulled. Then Check.
Try it yourself
using UnityEngine;
using UnityEngine.InputSystem;
// Space uses the first thing within reach.
public class Interactor : MonoBehaviour
{
public float reach = 1.5f;
void Update()
{
if (Keyboard.current.spaceKey.wasPressedThisFrame)
{
foreach (Collider c in Physics.OverlapSphere(transform.position, reach))
{
if (c.TryGetComponent(out IInteractable thing))
{
thing.Interact();
return;
}
}
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground