Well for sure, having colliders is going to be one of the worst ways to go about finding neighbors if you’re on a grid. What you should do instead: use the grid! When you create a conveyer belt, put it into a 2-dimensional array at its x,y position (use RoundToInt for this so that you don’t get screwed up by floating point imprecision).
Something like the following. (Depending on your scene setup you’ll probably want to modify the x and y so that they actually fit into your grid - negative numbers are no good, etc)
public class ConveyorBeltManager : MonoBehaviour {
public static ConveyorBelt[,] grid = new ConveyorBelt[50,50];
}
public class ConveyorBelt : MonoBehaviour {
void Awake() {
int x = Mathf.RoundToInt(transform.position.x);
int y = Mathf.RoundToInt(transform.position.y);
ConveyorBeltManager.grid[x,y] = this;
}
}
When the objects are all placed and in the array, loop through all of them, having it check the x,y position of each of its neighbors. (If the objects are expected to be placed/removed during the game, feel free to run this algorithm every frame - checking arrays like this is super fast.)
bool north = (ConveyorBeltManager.grid[x, y+1] != null); //whether we have a north neighbor
//repeat for the other directions
When you do this, you’ll have 4 bools, one for each direction, for whether or not there is a belt in that position. So now you need to turn those 4 bools into a reference to a sprite. There’s plenty of ways you can do this with varying degrees of complexity and efficiency. One of the conceptually simplest (albeit not the most elegant or most efficient) ways would probably be to use the filenames of the sprites as a dictionary key; if you name these files using a precise naming scheme, you can turn your 4 directions into a string.
//on the manager
public Sprite[] allSprites; //drag all your sprites into this array
public Dictionary<string, Sprite> spriteLookup = new Dictionary<string, Sprite>();
void Awake() {
foreach (Sprite s in allSprites) {
spriteLookup.Add(s.name, s);
}
}
// when determining neighbors
bool north, south, east, west; //fill as shown above
string filename = $"North_{north}_South_{south}_East_{east}_West_{west}";
Sprite mySprite = ConveyorBeltManager.spriteLookup[filename];
If your filenames are in the form of “North_True_South_False_East_True_West_False”, this should fetch the correct Sprite for your situation. (Make sure that you’re careful of capitalization, order, etc are precise, and that you have all 16 possible combinations) You’ll probably want to add some debug outputs of these string, some error tolerance (like checking spriteLookup.Contains before accessing it), etc.