Recap: FindNearest
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 36 of 50.
Challenge
MediumA 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 classHelperswith a generic methodFindNearest<T>(IEnumerable<T> items, Vector3 from)for any component type. It returns the item whose position is nearest tofrom, 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 logsChargingonce 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types