Menu
CoddyTech

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 icon

Challenge

Easy

Space should use the nearest thing, not the first.

  1. In Interactor, before the loop, add IInteractable nearest = null; and float best = Mathf.Infinity;.
  2. In the loop, keep any thing whose Vector3.Distance to the player is below best, with its distance.
  3. After the loop, call nearest.Interact() if nearest is 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;
                }
            }
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Game Architecture in Unity

Practice on your own: Unity playground