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
MediumSend the robot to the gems, nearest first, then to charge.
- In
Helpers.cs, write the static classHelperswith publicFindNearest<T>(IEnumerable<T> items, Vector3 from)for components: the nearest item, ornull. - In
Robot, each frame,MoveTothe nearestGemand destroy it on arrival. - With no gems left, go to the nearest
ChargePad, logChargingonce 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
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