Unity Tilemap - 扩展Tile的SceneView显示

效果

动画

 

[RequireComponent(typeof(Tilemap))]
public class TilemapCustomGizmos : MonoBehaviour
{
    [SerializeField]
    private Tilemap m_CachedTilemap;
    public Tilemap cachedTilemap
    {
        get
        {
            if (m_CachedTilemap == null)
                m_CachedTilemap = GetComponent<Tilemap>();
            return m_CachedTilemap;
        }
    }

    [Range(10, 50)]
    [SerializeField]
    private int m_FontSize = 30;

    private GUIStyle m_CachedStyle;
    private GUIStyle cachedStyle
    {
        get
        {
            if (m_CachedStyle == null)
            {
                var style = new GUIStyle(GUI.skin.label);
                m_CachedStyle = style;
                style.alignment = TextAnchor.MiddleCenter;
                style.normal.textColor = Color.white;
                //style.font = EditorGUIUtility.Load("Fonts/arial") as Font;
                style.fontSize = m_FontSize;
            }
            return m_CachedStyle;
        }
    }

    private GUIContent m_TipsContent = new GUIContent();

    private void OnDrawGizmos()
    {
        float handleSize = HandleUtility.GetHandleSize(Vector3.one);

        var style = cachedStyle;
        int dynamicFontSize = Mathf.FloorToInt(m_FontSize / handleSize);
        style.fontSize = dynamicFontSize;

        var tilemap = cachedTilemap;
        Vector3 cellHalfWSize = tilemap.cellSize * 0.5f;

        Handles.BeginGUI();
        {
            var allPositionsWithin = tilemap.cellBounds.allPositionsWithin;
            foreach (var cellPos in allPositionsWithin)
            {
                var tileBase = tilemap.GetTile(cellPos);
                var tile = tileBase as CustomTile;
                if (tile != null)
                {
                    if (!string.IsNullOrEmpty(tile.tips))
                    {
                        Vector3 cellWpos =  tilemap.CellToWorld(cellPos);
                        Vector3 cellCenterWpos = cellWpos + cellHalfWSize;
                        Vector2 cellCenterScPos = HandleUtility.WorldToGUIPoint(cellCenterWpos);

                        m_TipsContent.text = tile.tips;
                        Vector2 textPxSize = style.CalcSize(m_TipsContent);
                        Rect drawRect = new Rect(cellCenterScPos.x - textPxSize.x * 0.5f, 
                            cellCenterScPos.y - textPxSize.y * 0.5f, //左上角为(0, 0)
                            textPxSize.x, textPxSize.y);
                        //GUI.Box(drawRect, "");
                        GUI.Label(drawRect, m_TipsContent, style);
                    }
                }       
            }
        }
        Handles.EndGUI();
    }

}

 

[CreateAssetMenu(menuName = "2D/Tiles/CustomTile", order = 301)]
public class CustomTile : Tile
{
    [SerializeField]
    private string m_Tips = "";
    public string tips
    {
        get { return m_Tips; }
    }
}

 

posted @ 2026-04-23 00:18  yanghui01  阅读(6)  评论(0)    收藏  举报