Is this a valid scenario to break the rule/guideline and cache anyway?

I’m still very new to Game Development and Unity, and I’m wondering if a scenario I’ve run into is a valid time to cache out of convenience, or if there’s a better way to accomplish the same thing and avoid caching.

I’m making a simple tower defense game, and a tower needs to choose an attacker to target, until that target is gone. The tower needs to know which attacker it is targeting, and I can only think of two ways to do this.

  1. Cache the closest attacker, and check that the target still exists each loop. This way, I only need to search through all of the attackers and find the closest on occasion. However, this does cache a GameObject that I know will eventually be Destroyed.

  2. Re-find the closest attacker each loop. This requires searching through all of the attackers each time for each tower (which will become more time consuming with more attackers and towers). This will also not have the same behavior, because it may find a new closest attacker before the previous target has been destroyed.

Neither of these seem like the correct solution to me, but I can’t think of another (relatively) simple way to accomplish this task without caching.

1 Like

Caching can be a valid solution to this problem, but it’s important to keep in mind that caching comes with a cost in terms of memory usage and potential bugs due to stale data. In this particular scenario, caching the closest attacker can be a reasonable choice, but you’ll need to make sure to handle the case where the cached attacker is destroyed before the tower has finished attacking it.

An alternative approach you could consider is to use a data structure that efficiently stores and retrieves objects based on their distance from a given point. One such data structure is a spatial partitioning algorithm like a quadtree or a spatial hash. Using a spatial partitioning algorithm, you could quickly find the closest attacker to a given tower without having to search through all of the attackers every time. Additionally, as attackers move around the game world, you can update their position in the partitioning structure to keep track of their current location.

Implementing a spatial partitioning algorithm can require more upfront work than caching, but it can be a more robust and efficient solution in the long run, especially if you expect to have many towers and attackers in your game.

Does this help?

1 Like

This helps a ton, thanks! I’ll look into those data structures you mentioned, that seems like a much better solution than either of my simple implementations.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms