Detect nearest neighbours (and their neighbours...)

hi there!

i want to let a gameobject find out which other gameobjects of same kind are close to him (distance equals own width/height) and then let these GO's find other GO's of same kind, which are that close (like in a bubble game when a red bubble looks if another red one is near).

what is the best approach here? thnx!!!

One way that should work for many kinds of games would be to use Unity colliders to detect other objects that are nearby. Specifically, try Physics.OverlapSphere to find all colliders in the scene that fall within a sphere centered on the object that you want to find the neighbors of.

Each game object would then store a list of its neighbors. Depending on the game, you might need to update these lists frequently, or not at all.

Will this scheme work for all games? No. There are many ways to do it, and how you do it depends on the situation. But Unity's physics engine is already doing lots of tricks to detect collisions quickly. So using it to find the neighbors should perform well even if you have a lot of objects in your scene.

A separate question is how to store the answers. This depends again on the game and what you want to do with the information. A simple approach is for each object to store a list of references, the list of all its neighboring GameObjects. But you might need to do it differently, for example keep separate lists of red and blue neighbors, or you might need to sort the list by distance so that the closest objects are always first.

If you're working with a grid, you have another option: Hashtables.

Hashtables have proven invaluable to me many a time when I wanted the tiles in a grid to know their neighbors. What you do is this (psuedocode):

  • When generating the grid, store each the Transform of each gameObject you instantiate in a hashtable, using the position as the key (something like `transform.position.ToString()`).
  • After you've finished instantiating all your objects (it's crucial to wait to the end), loop through your hashtable, which should have a reference to all the tiles in the scene.
  • For each entry, get the Transforms of the objects around it and store them in either a hashtable or an array on the gameObject. You can then access its neighbors by looking at this hashtable.

To iterate through a hashtable, you can use this code:

foreach(DictionaryEntry currentEntry in hashtableName) {
    string currentEntryKey = currentEntry.Key;
    Transform currentEntryTransform = hashtableName[currentEntry.Key];
}

That's just some useful code for traversing hashtables. (Note that using Transform is not necessary; you can change it to reflect whatever variables you want to store in the hashtable) My answer may or may not be completely unrelated to your question, but it's useful for referencing if you ever have to know the neighbors of an object in a grid. :)