| | |
| | | public Vector2 spacing = new Vector2(10f, 10f); // 元素间距 |
| | | public int rows = 7; // 固定行数 |
| | | |
| | | private void OnRectTransformDimensionsChange() => UpdateLayout(); |
| | | private void OnTransformChildrenChanged() => UpdateLayout(); |
| | | private bool _isDirty = true; //优化新增:脏标记与计时器 初始设为 true,确保第一帧会排版 |
| | | private float _checkTimer = 0f; |
| | | private const float CHECK_INTERVAL = 0.1f; // 100ms 检查间隔 |
| | | |
| | | #if UNITY_EDITOR |
| | | /// <summary> |
| | | /// 供外部或子元素调用,标记当前网格需要重新排版 |
| | | /// </summary> |
| | | public void MarkAsDirty() |
| | | { |
| | | _isDirty = true; |
| | | } |
| | | |
| | | // 尺寸或子节点数量发生变化时,同样只打上脏标记 |
| | | private void OnRectTransformDimensionsChange() => MarkAsDirty(); |
| | | private void OnTransformChildrenChanged() => MarkAsDirty(); |
| | | |
| | | private void Update() |
| | | { |
| | | if (!Application.isPlaying) UpdateLayout(); |
| | | } |
| | | #if UNITY_EDITOR |
| | | // 编辑器非运行状态下(Edit Mode)Update 帧率不稳定,为了方便拖拽预览,依然有脏标记就立即更新 |
| | | if (!Application.isPlaying) |
| | | { |
| | | if (_isDirty) |
| | | { |
| | | UpdateLayout(); |
| | | _isDirty = false; |
| | | } |
| | | return; |
| | | } |
| | | #endif |
| | | |
| | | // 运行时(Play Mode)每 100ms 轮询一次 |
| | | _checkTimer += Time.deltaTime; |
| | | if (_checkTimer >= CHECK_INTERVAL) |
| | | { |
| | | if (_isDirty) |
| | | { |
| | | UpdateLayout(); |
| | | _isDirty = false; // 排版完成后,清除标志位 |
| | | } |
| | | _checkTimer = 0f; // 重置计时器 |
| | | } |
| | | } |
| | | |
| | | public void UpdateLayout() |
| | | { |
| | | if (rows <= 0 || transform.childCount == 0) return; |