6
votes

I'm trying to add one of my scriptable tiles to my Unity Tilemap during runtime. I can paint the tile in the editor and everything looks fine but I would like to add it during runtime.

I tried instantiating the ScriptableObject asset itself, but it does not have the correct sprites it needs that the generated tile asset has in the editor. Also, I don't believe I should be instantiating the ScriptableObject asset for each tile since one asset is meant to be shared for all of the same tiles on the map.

The Tilemap API provides a way to add a tile, but no instructions or example of how to create the tile.

3

3 Answers

0
votes

This is kinda off the top of my head, but I was messing around with something similar yesterday, instantiating a tile on click.

Vector3Int tilePos = map.WorldToCell(mousePos);

    YourTileClass tileInstance = ScriptableObject.CreateInstance<YourTileClass>();

    Texture2D tex = Resources.Load<Texture2D>("tileTexture") as Texture2D;

    Sprite sprite = new Sprite();

    sprite = Sprite.Create(tex, new Rect(0, 0, 400, 400), new Vector2(0.5f, 0.5f));

    Tile tile = Resources.Load<Tile>("tileInstance") as Tile;

    tileInstance .sprite = sprite;

    yourTileMap.SetTile(tilePos , tile);

I am not 100% if that is the best way to do it, but it worked for me. Let me know if that does not work and I will double check the actual file.

0
votes

Sorry, I can't comment, but not knowing what you've tried so far, have you tried assigning the ruletile in the inspector and then just assigning it with SetTile at runtime whenever you need to? From the sounds of it this should achieve what you're trying to do

public Tilemap tilemap;
public MyRuleTile myRuleTile;

tilemap.SetTile(coordinate, myRuleTile);
0
votes

Assuming your ScriptableObject is inheriting from TileBase object you can do the following:

 public Tilemap tilemap; 
 public TileBase tileToDraw; //Object to draw at runtime

 //Get tilemap position from the worldposition
 Vector3Int tilemapReferencePosition = tilemap.WorldToCell(reference.transform.position);//this can be the position of another gameObject e.g your Player or MousePosition

roadTileMap.SetTile(tilemapReferencePosition, tileToDraw);

I recently used something similar for a Fire Emblem style RPG where I wanted to draw all the potential directions a spell can be cast before casting it and I ended up with the following function

public void DrawPreAttack(GameObject reference, Spell spell) {
    Vector3Int gridReferencePos = preAttackTileMap.WorldToCell(reference.transform.position);
    foreach (Vector2 direction in spell.validDirections) {
        for (int i = 0; i <= spell.maxDistance; i++) {
            preAttackTileMap.SetTile(new Vector3Int(gridReferencePos.x + (i * (int)direction.x) , gridReferencePos.y + (i * (int)direction.y) , 0), preAttackTile);
        }
    }
}