Object closest to the finish line

this line is probably the slowest one,

Ball[] balls= FindObjectsOfType<Ball>();

so instead of always searching them, try something like:

  • keep list/array/dictionary of spawned objects (when you instantiate, add to list, when you destroy, remove from it)
  • or, if objects are spawned under parent transform, can try looping the children Unity - Scripting API: Transform.GetChild

Even better if objects are moving on a plane, in 1 direction,
then could just compare X or Y or Z value directly (who is closest has biggest value, without measuring (full 3d) distance)

ps. can embed code with Using code tags properly

1 Like