Menu
CoddyTech

Recap: FindNearest

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 45 of 64.

This chapter wrote code that works for any type: extension methods, a generic base class and generic helpers. Here one generic search finds both the gems and the charging pads.

challenge icon

Challenge

Medium

Send the robot to the gems, nearest first, then to charge.

  1. In Helpers.cs, write the static class Helpers with public FindNearest<T>(IEnumerable<T> items, Vector3 from) for components: the nearest item, or null.
  2. In Robot, each frame, MoveTo the nearest Gem and destroy it on arrival.
  3. With no gems left, go to the nearest ChargePad, log Charging once and stay.

Press Play: the robot sweeps up the gems. Then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

// Helpers.FindNearest<T>: the item nearest to a point, or null
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