@@ -91,6 +91,9 @@ class TiledMap {
9191 List <EditorSetting > editorSettings;
9292 CustomProperties properties;
9393
94+ // Cache the object by ID when accessed.
95+ Map <int , TiledObject >? _cachedObjects;
96+
9497 // only for hexagonal maps:
9598 int ? hexSideLength;
9699 StaggerAxis ? staggerAxis;
@@ -279,6 +282,27 @@ class TiledMap {
279282 throw ArgumentError ('Layer $name not found' );
280283 }
281284
285+ /// Finds the [TiledObject] in this map with the unique [id] .
286+ /// Objects have map wide unique IDs which are never reused.
287+ /// https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#object
288+ ///
289+ /// This reads through a cached map of all the objects so it does not
290+ /// need to loop through all the object layers each time.
291+ ///
292+ /// Returns null if not found.
293+ TiledObject ? objectById (int id) {
294+ if (_cachedObjects == null ) {
295+ _cachedObjects = {};
296+ layers.whereType <ObjectGroup >().forEach ((objectGroup) {
297+ for (final object in objectGroup.objects) {
298+ _cachedObjects! [object.id] = object;
299+ }
300+ });
301+ }
302+
303+ return _cachedObjects? [id];
304+ }
305+
282306 Tileset tilesetByName (String name) {
283307 return tilesets.firstWhere (
284308 (element) => element.name == name,
0 commit comments