Menu
CoddyTech

Recap: FindNearest

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

challenge icon

Challenge

Medium

A cleaning robot collects gems, then goes to charge. Gem and ChargePad are empty marker scripts (ready), and the robot has MoveTo(point), which steps it toward a point at speed and returns true once it is there.

  • In Helpers.cs, write a static class Helpers with a generic method FindNearest<T>(IEnumerable<T> items, Vector3 from) for any component type. It returns the item whose position is nearest to from, or null when there are no items.
  • In Robot.cs, every frame the robot heads for the nearest gem in the scene, from where it is now, and destroys the gem when it gets there.
  • When no gems are left, the robot heads for the nearest ChargePad. On arrival it logs Charging once and stays there.

Use FindNearest for both the gems and the pads. Press Play, watch the robot, then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

// Helpers.FindNearest<T>: the item nearest to a point, or null

All lessons in Game Architecture in Unity