Search code examples
c#unity-game-enginegameobject

Unity c# rooms finding close rooms


I have a Unity game I'm working on. Currently it’s at a basic state, but the goal is to somewhat replicate the gameplay of old style telnet MUDs in a graphical fashion. Map construction at this phase is manual, not automatic, although that’s planned for later. I can easily place the rooms in a 2-d grid, each a number of whole units away from each other, on the x and y axis. I’m at the stage where I’ve got several “Room” gameObjects, and they each have a C# script (let’s call the script “a_room.cs”). Each script has a public gameObject variable for the rooms that are north, south, east, and west of that particular “room”.

My question; is there a way to have each and every “room”, either at runtime or in-editor, figure on its own out which “rooms” are closest to each of its particular cardinal direction? Taking into account that there may be several rooms in a given direction and only the closest is desired, as well as the fact that there may be NO rooms in that direction?

I don't necessarily need code as an answer, the logic and important functions are what I'm after.

Also; if there’s something blatantly wrong with this method of thought alternative suggestions are appreciated.


Solution

  • You could have a global list containing all these a_room objects.

    Ideally, you can make the N/S/E/W assignments while instantiating the rooms itself. Ex: After R1 is created, R2 is created to the East of R1 and also assigned as the EastRoom of R1.

    Otherwise, since the rooms are placed at a certain 'n' units away from the next one (horizontally or vertically), you can search the list to see what rooms are placed at the neighbouring locations to a certain room. Ex: If R1 is known to be at position (x,y), search through the global list to find a room whose location is (x+n, y) and assign that as the EastRoom of R1; the room at (x-n, y) as the WestRoom of R1, etc.

    I hope that helps!