I’m fairly new to Unity but have more experience using C#. I’m trying to create a 2d array of objects from a class I made called Tile for the purpose of creating a game board.
Here’s a bit of the C# code I have, I’ve looked at different ways of trying to make it work in unity but I haven’t had any luck. Thank you.
public static void Main()
{
Tile[,] tileArray;
tileArray = new Tile[25, 25];
for (int i = 0; i < 25; i++)
{
for (int x = 0; x < 25; x++)
{
tileArray[x, i] = new Tile(x, i);
Console.WriteLine(tileArray[x, i].X + " " + tileArray[x, i].Y);
}
}
}
To expand on RalphT’s reply, a Unity prefab with a script really is an instance of a class, and will NEW a copy when you spawn it. So, most people never explicitly declare and NEW the Tile class.
Instead, make a fresh script named Tile. Notice how Tile is technically a class. Attach that script to a flat tile-shaped cube and prefab it. Then just Instantiate
a 2D array of Transforms (example in the docs.) Each Instantiate gives a free new Tile
AND it will initialize for free by coping public vars from whichever prefab you used (very easy to make 5 types of tile that way, if you make 5 prefabs. All might have different colors, and diff settings in Tile script.)
Your method will also work, and is more “programmery.” It looks like this:
// define inside the BigGrid script:
class Tile {
public bool isRed, likesDucks; // whatever vars you want
public int numOfCows; // more variables
// VVV New line VVV
public Transform myTile; // hold copy of spawned tile gameObject
}
Then add this one line in your loop: tileArray[x,i].myTile = Instantiate(tilePrefab, ..... );
. You can now write normal code that can “reach down” to the actual tile model. Ex: tile[3,4].myTile.renderer.material.Color = Color.green;
Look up Prefabs and Instantiate. What you should do is create your tile and copy it down into a prefab directory then instantiate instances of it and move them to where you want them.
The entry point into your code in Unity is a function called Start
, not Main
.