- Home /
Tilemap : Instantiate new tile on click
Hello
I am quite new to Unity, and have been playing around with the new Tilemap functionality, and I am a bit stuck.
I am trying to instantiate a new tile onto the tilemap at the mouses position when I click the button, the code I am using is :
void Update()
{
if (Input.GetMouseButtonDown(0))
{
createTileAtPoint(Input.mousePosition);
}
}
void createTileAtPoint(Vector3 pos)
{
pen.SetTile(pen.WorldToCell(pos), ScriptableObject.CreateInstance<GameTile>());
}
Where GameTile is :
public class GameTile : Tile {
[SerializeField]
private Sprite[] gameSprites;
[SerializeField]
private Sprite preview;
public int movePenalty = 0;
public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
{
base.GetTileData(position, tilemap, ref tileData);
}
public override void RefreshTile(Vector3Int position, ITilemap tilemap)
{
base.RefreshTile(position, tilemap);
}
}
The code does not error, but no tile appears. I am assuming this is because the sprite property of the newly instanced GameTile is empty, but I am a bit lost on how I would define this in code.
I would be incredibly grateful if someone could offer some advice, or point me towards the relevant documentation.
Thanks in advance :)
Answer by ryandotdee · Dec 20, 2017 at 12:47 AM
So I was being a bit thick. read up on creating sprites ( I was too focused on Tilemaps )
Texture2D tex = Resources.Load<Texture2D>("grass_tile_3") as Texture2D;
Sprite sprite = new Sprite();
sprite = Sprite.Create(tex, new Rect(0, 0, 133, 133), new Vector2(0.5f, 0.5f));
So added that to my GameTile, still not showing. It turns out the reason for this was that as I am working in 2d, the Input.mouseposition was returning a position not present in my tilemap, so needed to use Camera.main.ScreenToWorldPoint(Input.mousePosition)
All working now :)