展前冒死重构
This commit is contained in:
@@ -24,17 +24,21 @@ public sealed class UICanvasMatchFitter : MonoBehaviour
|
||||
private void OnEnable()
|
||||
{
|
||||
scaler = GetComponent<CanvasScaler>();
|
||||
Apply();
|
||||
// 切换 UI 时 Canvas 激活会走到这里。若只是设 match 而不立即同步,
|
||||
// 序列化的旧 match(=1) 会在激活当帧先生效、下一帧才被本组件改成正确值,
|
||||
// 造成偏心元素(如偶像名字 anchoredX≈-201)"先偏后正"的一帧跳动。
|
||||
// 故激活时同步应用并强制刷新 Canvas,消除这一帧时序。
|
||||
Apply(forceCanvasUpdate: true);
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// 分辨率/窗口变化时才重算。
|
||||
float aspect = (float)Screen.width / Mathf.Max(1, Screen.height);
|
||||
if (Mathf.Abs(aspect - lastAspect) > 0.0001f) Apply();
|
||||
if (Mathf.Abs(aspect - lastAspect) > 0.0001f) Apply(forceCanvasUpdate: false);
|
||||
}
|
||||
|
||||
private void Apply()
|
||||
private void Apply(bool forceCanvasUpdate)
|
||||
{
|
||||
if (scaler == null) scaler = GetComponent<CanvasScaler>();
|
||||
if (scaler == null) return;
|
||||
@@ -45,6 +49,16 @@ public sealed class UICanvasMatchFitter : MonoBehaviour
|
||||
|
||||
scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
|
||||
// 更宽→锁高度(1);更窄→锁宽度(0)。等于始终匹配“更受限的一侧”,设计区域完整可见。
|
||||
scaler.matchWidthOrHeight = aspect >= DesignAspect ? 1f : 0f;
|
||||
float target = aspect >= DesignAspect ? 1f : 0f;
|
||||
bool changed = !Mathf.Approximately(scaler.matchWidthOrHeight, target);
|
||||
scaler.matchWidthOrHeight = target;
|
||||
|
||||
if (forceCanvasUpdate && changed)
|
||||
{
|
||||
// 让 CanvasScaler 立即按新 match 重算 scaleFactor、并在同一帧完成布局,
|
||||
// 避免"旧 scale 定位一帧 → 下一帧修正"的可见跳动。
|
||||
// ForceUpdateCanvases 会驱动 CanvasScaler 重算并刷新布局。
|
||||
Canvas.ForceUpdateCanvases();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user