Unity for coders

I’ve been using Unity for a few years now, and while I can start off a project well I always seem to run into the same issues that make me feel like I’m not using it correctly.

For example, I’ve gone back to basics and I’m trying to create a simple Minesweeper game. If I were creating this anywhere else I’d define each square as an object with different properties and methods like mined, number of neighbour mines, reveal, explode, etc. In Unity, I’ve got prefab models for all the graphics. I’ve got a script that’s attached to the camera that sets up the grid and it all looks fine. I’ve got a script attached to the tile prefab that has methods like Reveal. But now that I’m trying to get things to interact with each other, I’m really struggling.

For example, I’d love to have the tiles in an array and then use recursion for reveals: (pseudo code so don’t focus on it)

public void Reveal() {
  renderer.enabled = false;
  if (tiles[x-1,y].value == 0 ) { // repeat for all other neighbours
    tiles[x-1,y].Reveal();
  }
}

But I can’t just do that because the tile is a GameObject and I can’t talk directly to the code. I can probably do it through the Inspector and dragging and dropping the script into a public variable, or using GetComponent and types, but it doesn’t seem like the right way to go. What would be really simple in plain JavaScript, for example, takes a lot more effort in Unity.
What’s the secret sauce that I’m missing? Can someone help me have that ding moment where it all slots together?

Unity Answers is intended for specific, technical questions that can be answered. This sounds like a discussion topic that would be better suited to The Forums.

However, I’m not quite sure what the problem is - what do you mean by “the tile is a GameObject and I can’t talk directly to the code”?

There is no simpler way. You access another component with a reference. You get a reference via the inspector, or by using GetComponent. This is not really any different to regular object orientated programming. There has never been a way to access an instance of a class without having a reference to the class from somewhere.

It is quite common to store references to components, instead of calling GetComponent every frame. In your case it might be relevant for each GameObject to have a reference to each of its neighbours. You would set this up in Awake or Start. Another alternate structure that pops to mind is to have a single manager class that stores all of the references by x, y position, you can then access each one by index.

Another common alternative is to write all of your code as regular C# and just use your MonoBehaviours as the final interface. It is possible to build the entire game with only a thin layer between the game code and Unity. You still can’t magically talk to code you have no reference to.