Hi, I have been trying to create a grid for a game where the player starts off in the middle and have the choice of 4 squares to pick and when they buy a square it makes the adjacent squares visible, I couldn’t find out how to make the grid unlimited in size so for now it is 7x7, below is a picture of what it looks like all together and what it looks like in-game when only 2 spaces are owned.
-
Each button in the grid is a prefab being instantiated upon startup.
-
Each one has a number on creation from 1 to 49 starting from the top left corner, and that number has been saved as the variable “squareValue” for each of them.
.
I’ve been trying to write a series of IF statements to tell the buttons to show themselves if an adjacent button has been clicked, but also to not check for buttons to the left if it’s on the left edge, or on the right if it’s on the right edge, etc.
This almost works apart from I keep getting 2 problems:
- I keep getting a repeated set of errors in-game when I click a second button, clicking the first button doesn’t come up with it, the error is “NullReferenceException: Object reference not set to an instance of an object” and it points to the lines in this series of statements saying “if (oneLess.GetComponent().slimeSpawned == true)”.
- The second problem is sometimes the buttons won’t appear when adjacent ones are clicked, this almost always happens with the top row and sometimes on the other edges.
.
I’ve spent a lot of today just staring at the code and changing parts to weed out the cause of the problems but I haven’t been able to get any closer to figuring out what’s wrong.
void Update()
{
GameObject gameManagerObject = GameObject.Find("GameManager");
GameManager gM = gameManagerObject.GetComponent<GameManager>();
textComponent.text = gM.newSquareCost.ToString();
if ((squareValue + 6) % 7 != 0)
{
GameObject oneLess = GameObject.Find((squareValue - 1).ToString());
if (oneLess.GetComponent<Square>().slimeSpawned == true)
{
gM.CanvasGroupChanger(true, squareGroup);
}
}
if (squareValue % 7 != 0)
{
GameObject oneMore = GameObject.Find((squareValue + 1).ToString());
if (oneMore.GetComponent<Square>().slimeSpawned == true)
{
gM.CanvasGroupChanger(true, squareGroup);
}
}
if ((squareValue - 7) > 0)
{
GameObject sevenLess = GameObject.Find((squareValue - 7).ToString());
if (sevenLess.GetComponent<Square>().slimeSpawned == true)
{
gM.CanvasGroupChanger(true, squareGroup);
}
}
if ((squareValue + 7) < 50)
{
GameObject sevenMore = GameObject.Find((squareValue + 7).ToString());
if (sevenMore.GetComponent<Square>().slimeSpawned == true)
{
gM.CanvasGroupChanger(true, squareGroup);
}
}
}
tavro
4
Another solution would be to have your Squares be aware of their row and column positions, like this:

Then simply set their name in the Awake-method or when they are instantiated.
You could then get all the neighbours based on their row and column, like this: