Skip to content

Instantly share code, notes, and snippets.

@Frank-Buss
Created June 27, 2020 09:02
Show Gist options
  • Save Frank-Buss/6412da3e6ed0582c24da092cbc2a834a to your computer and use it in GitHub Desktop.
Save Frank-Buss/6412da3e6ed0582c24da092cbc2a834a to your computer and use it in GitHub Desktop.
load a tileset PNG from the streamingAssets folder, and create a Unity Tilemap and all necessary objects with a C# script
using UnityEngine;
using UnityEngine.Tilemaps;
// Load a tileset PNG from the streamingAssets folder, and create a
// Unity Tilemap and all necessary objects with a C# script.
// Attach this script to an empty GameObject.
// Copyright 2020 by Frank Buss. Can be used for free in any project.
public class TilemapTest : MonoBehaviour
{
public static Texture2D LoadTexture(string filename)
{
// load an image file rom the streamAssets folder
byte[] pngBytes = System.IO.File.ReadAllBytes(Application.streamingAssetsPath + "/" + filename);
// create a Texture2D with it
Texture texture = new Texture();
Texture2D tex2d = new Texture2D(2, 2);
tex2d.filterMode = FilterMode.Point;
tex2d.LoadImage(pngBytes);
return tex2d;
}
private Tile CreateTile(Texture2D tileset, int x0, int y0, int width, int height)
{
// create a sprite from a part of the texture
Sprite tileSprite = Sprite.Create(tileset, new Rect(x0, y0, width, height), new Vector2(0, 0), width);
// create a tile with the sprite
Tile tile = ScriptableObject.CreateInstance(typeof(Tile)) as Tile;
tile.sprite = tileSprite;
return tile;
}
public void Awake()
{
// create 2 tiles from a tileset with 32x32 pixel tiles, which have one pixel spacing
Texture2D tileset = LoadTexture("tmw_desert_spacing.png");
Tile tileA = CreateTile(tileset, 1, 1, 32, 32);
Tile tileB = CreateTile(tileset, 34, 1, 32, 32);
// create the Unity tilemap gameobjects
GameObject gridGameObject = new GameObject("Tilemap Grid");
var grid = gridGameObject.AddComponent<Grid>();
GameObject tilemapGameObject = new GameObject("Tilemap");
tilemapGameObject.transform.parent = gridGameObject.transform;
var tm = tilemapGameObject.AddComponent<Tilemap>();
tilemapGameObject.AddComponent<TilemapRenderer>();
// create a checkerboard with the 2 tiles
Vector2Int size = new Vector2Int(8, 8);
Vector3Int[] positions = new Vector3Int[size.x * size.y];
TileBase[] tileArray = new TileBase[positions.Length];
int index = 0;
for (int y = 0; y < size.y; y++)
{
for (int x = 0; x < size.x; x++)
{
positions[index] = new Vector3Int(x, y, 0);
tileArray[index] = (x + y) % 2 == 0 ? tileA : tileB;
index++;
}
}
tm.SetTiles(positions, tileArray);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment