This does not seem like a "newbie" question at all. It seems fairly clear that you just want to lay down tiles programmatically rather than via the editor.
I ran in to the same question because I wanted to populate my tiles based on a terrain generator. It's surprising to me that the documentation is so lacking in this regard, and every tutorial out there seems to assume you are hand-authoring your tile layouts.
Here's what worked for me:
This first snippet does not answer your question, but here's my test code to lay down alternating tiles in a checkerboard pattern (I just have two tiles, "water" and "land")
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
Vector3Int p = new Vector3Int(x,y,0);
bool odd = (x + y) % 2 == 1;
Tile tile = odd ? water : land;
tilemap.SetTile(p, tile);
}
}
In order to get an instance of a Tile
, I found that two different methods worked:
Method 1: Hook up Tiles to properties using Editor
In the MonoBehaviour
class where you are writing the code to programmatically generate the tile layout, expose some public properties:
public Tile water;
public Tile land;
Then in the Unity Inspector, these fields will appear. If you press the little bullseye next to these properties it will open up a "Select Tile" window where you should be able to see any tiles that you have previously added to the Tile Palette
Method 2: Programmatically Create Tile from Texture in Resources folder
If you have a lot of different tile types, manually hooking up properties as described above may become tedious and annoying.
Also if you have some intelligent naming scheme for your tiles which you want to take advantage of in code, it will probably make more sense to use this second method. (e.g. maybe you have four variants of water and four of land that are called water_01, water_02, water_03, water_04, land_01, etc., then you could easily write some code to load all textures "water_"+n for n from 1 to numVariants).
Here's what worked for me to load and create a Tile from a 128x128 texture saved as Assets/Resources/Textures/water.png
:
Tile water = new Tile();
Texture2D texture = Resources.Load<Texture2D>("Textures/water") as Texture2D;
water.sprite = Sprite.Create(texture,
new Rect(0, 0, 128, 128), // section of texture to use
new Vector2(0.5f, 0.5f), // pivot in centre
128, // pixels per unity tile grid unit
1,
SpriteMeshType.Tight,
Vector4.zero
);