Highlighting Tiles

Through scripting, I’m changing the color of the tile Image whenever OnMouseDown() is triggered for a tile. It’s going to represent where the player is headed. However, if the character stops on the tile OR changes to go to another tile, then the color should go back to normal.

I’m stuck at the “disabling color” part. How can I tell the tile that it needs to turn the color off if another tile is selected, or the player has stopped moving? All the tiles are from one prefab, so I’m confused how I can communicate between them…

public class tileScript : MonoBehaviour
{
    [SerializeField] playerScript playerScript;
    public bool toolOccupied;
    public bool playerOccupied;

    // Update is called once per frame
    void Update()
    {
        TileColor();
    }

    public void TileColor()
    {
        if (playerOccupied && !playerScript.moving)
        {
            GetComponent<Image>().color = new Color32(0, 0, 0, 0);
        }
    }

    private void OnMouseOver()
    {
        if(Input.GetMouseButtonDown(1) && !playerOccupied && !toolOccupied)
        {
            playerScript.tileX = transform.position.x;
            playerScript.tileY = transform.position.y;
            GetComponent<Image>().color = new Color32(0, 255, 0, 225);
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            playerOccupied = true;
        }

        if (collision.gameObject.tag == "Tool")
        {
            toolOccupied = true;
        }

    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            playerOccupied = false;
        }
    }

}

Any help?

What I do for my UI is put transluscent planes over icons and show/hide them as I see fit. It looks just like highlighting. I don’t know how your tile system is visually, but perhaps you could do something similar.

Since each tile is presumably linked to the same material, which is in turn linked to the same image, changing the image will change them all. Another approach you could take would be to duplicate the image in your folder, change that one permanently, and assign it to a new material. Then, you could just switch the material at runtime when moused-over or clicked or whatever.

You don’t mean tiles as in tiles from a tilemap do you?

Store the position of the last tile on OnMouseOver, and when you select a new tile, revert the color of the stored position.

1 Like

Thank you! I added a Vector2 to store the destination position for the character. Then added an if statement to the tile, saying if the destination.transform was equal to the tile.transform, then it should highlight. Otherwise, return to normal color.