Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Returning all objects of same type that are 'touching' in a grid?

Discussion in 'Scripting' started by iTZi, Mar 9, 2023.

  1. iTZi

    iTZi

    Joined:
    Sep 22, 2013
    Posts:
    2
    Hi,

    I have a "grid" Dictionary with a Vector2 key and a int value and want to know the Vector2 position of all of the same int value that are 'touching' each other from a specified outset point.

    Example: From position (0,4), which is a "7", I want to know how many 7's are touching that 7.

    0 0 0 7 7
    0 0 0 0 0
    7 7 7 0 0
    7 7 0 0 7

    So here it would return the Vector2 values in the Dictionary of the 5 x 7's in the bottom left corner, but not any of the other 7's

    How would i be able to achieve this?
     
  2. tomfulghum

    tomfulghum

    Joined:
    May 8, 2017
    Posts:
    69
    You could use some kind of flood fill algorithm. In the tutorial, they're filling adjacent pixels of the same color, but just counting adjacent cells with the same value isn't any different.
     
    Kurt-Dekker and karliss_coldwild like this.
  3. iTZi

    iTZi

    Joined:
    Sep 22, 2013
    Posts:
    2
    Thanks! Found a good tutorial on the subject and got it working after a few hour.
    Much appreciated
     
    tomfulghum and Kurt-Dekker like this.